Beispiele · PyTorch
Transformer-Textklassifikator in PyTorch
Ein kompakter Transformer, der Texte in vier Klassen einsortiert: Token-Embeddings plus gelernte Positionen laufen durch zwei Encoder-Schichten mit Self-Attention, und der Mittelwert über alle Positionen geht an den Klassifikator.
- Code
- PyTorch
- Aufgabe
- Textklassifikation
- Eingabe
- 64
- Bausteine
- 7
- Trainierbare Parameter
- 1.611.268
Was das Netz macht
Der Input nimmt 64 Token-IDs. Embedding bildet jede auf 128 Zahlen ab (10.000 × 128 = 1.280.000 Parameter), und PositionalEmbedding addiert für jede Position einen gelernten Vektor, weil Self-Attention für sich genommen die Reihenfolge der Tokens nicht kennt.
Der TransformerEncoder hat zwei Schichten, jede mit Self-Attention aus vier Köpfen und einem Feed-Forward-Teil mit 256 Einheiten: zusammen 264.960 Parameter. In jeder Schicht kann jede Position jede andere betrachten. SequencePool bildet den Mittelwert über die 64 Positionen, LayerNorm normalisiert den Vektor der Länge 128, und eine Linear-Schicht liefert die vier Klassen-Scores. Das Netz hat 1.611.268 Parameter.
Wann es passt
- Für die Einordnung kurzer und mittellanger Texte nach Thema oder Absicht, wenn weit auseinanderliegende Wörter voneinander abhängen.
- Um die Teile eines Transformer-Encoders mit echten Formen kennenzulernen, bevor Sie mit großen vortrainierten Modellen arbeiten.
- Für längere Texte erhöhen Sie
max_lendes Positions-Embeddings und die Länge des Inputs; der Aufwand der Attention wächst mit dem Quadrat der Länge.
Schichten, Formen und Parameter
| Baustein | Typ | Einstellungen | Ausgabe | Parameter |
|---|---|---|---|---|
tokens | Input | shape=64 dtype=long | 64 | 0 |
embed | Embedding | num_embeddings=10000 embedding_dim=128 | 64 × 128 | 1.280.000 |
pos | PositionalEmbedding | max_len=512 | 64 × 128 | 65.536 |
encoder | TransformerEncoder | nhead=4 dim_feedforward=256 num_layers=2 | 64 × 128 | 264.960 |
pool | SequencePool | mode=mean | 128 | 0 |
norm | LayerNorm | Standardwerte | 128 | 256 |
fc | Linear | out_features=4 | 4 | 516 |
| Gesamt | 1.611.268 | |||
Training in Brick DNN
Textmodelle trainieren in Brick DNN bisher auf Demodaten, was prüft, dass das Netz lernt. Das exportierte PyTorch-Modul ist bereit für Ihr eigenes Training auf zerlegten Texten: 64 Token-IDs je Text aus einem Vokabular von 10.000.
Der erzeugte Code
Das ist das PyTorch-Skript, das der Code-Dialog des Editors aus dem Graphen oben erzeugt (transformer_classifier.py): ein nn.Module mit einem Attribut je Schicht und einer forward-Methode, dazu ein Test, der einen zufälligen Batch durch das Netz schickt, und, weil das Netz einen flachen Vektor nimmt und einen ausgibt, eine Trainingsschleife für CSV-Dateien (--csv daten.csv). Es braucht nur PyTorch.
# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""NeuralNetwork: generated with Brick DNN.
Input: (batch, 64) (integer token ids)
Output: (batch, 4)
Trainable parameters: 1,611,268
Print the model and run it on a random batch:
python this_file.py
Train it on Topics, a built-in text dataset of Brick DNN (generated below:
the same texts as in Brick DNN), then classify new texts with the saved model:
python this_file.py --train --epochs 10
python this_file.py --predict "your text"
Log the training to Brick DNN, to see its curves next to the runs trained there (the
runs page): create an API token on the page API tokens (one that may only log runs is
enough) and set it in the environment before you train:
export BRICKDNN_TOKEN=<your token>
python this_file.py --train --epochs 10
It sends the loss and the accuracy of every epoch, the settings, the name of the dataset
and the test accuracy to BRICKDNN_URL (default https://brickdnn.com). Without
BRICKDNN_TOKEN nothing is sent and the script runs offline with the same results; a
network error never stops the training. The token is never stored in this file.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import re
import sys
import time
import urllib.error
import urllib.request
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
class NeuralNetwork(nn.Module):
def __init__(self) -> None:
super().__init__()
self.embedding_1 = nn.Embedding(10000, 128)
self.pos_embedding_1 = nn.Embedding(512, 128)
self.encoder_1 = nn.TransformerEncoder(
nn.TransformerEncoderLayer(
d_model=128, nhead=4, dim_feedforward=256,
dropout=0.1, batch_first=True,
),
num_layers=2,
)
self.layernorm_1 = nn.LayerNorm(128)
self.linear_1 = nn.Linear(128, 4)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.embedding_1(x)
x = x + self.pos_embedding_1(torch.arange(x.size(1), device=x.device))
x = self.encoder_1(x)
x = x.mean(dim=1)
x = self.layernorm_1(x)
x = self.linear_1(x)
return x
def count_parameters(model: nn.Module) -> int:
return sum(p.numel() for p in model.parameters() if p.requires_grad)
# --------------------------------------------------------------------------- #
# The built-in text datasets of Brick DNN (brickdnn/training/textsets.py)
# --------------------------------------------------------------------------- #
TEXT_PAD = "<pad>" # id 0: fills a sequence up to its length
TEXT_UNK = "<unk>" # id 1: a word that is not in the vocabulary
def _words(text: str) -> list[str]:
return text.split()
# --------------------------------------------------------------------------- #
# Sentiment: short reviews with negations, intensifiers and "but"
# --------------------------------------------------------------------------- #
_SUBJECTS = _words(
"food soup pizza coffee dessert service staff waiter room bed view hotel beach trip "
"flight train guide museum movie plot ending story actor music song album concert show "
"book game app phone laptop camera screen battery price course teacher lesson"
)
_DETERMINERS = _words("the our my this their")
_VERBS = _words("was is seemed felt looked")
_POSITIVE = _words(
"good great excellent wonderful lovely amazing pleasant fantastic superb nice "
"delightful brilliant charming enjoyable fun perfect solid impressive friendly helpful "
"clean fresh comfortable beautiful tasty smooth reliable clever gripping cosy"
)
_NEGATIVE = _words(
"bad awful terrible poor boring dull horrible disappointing bland rude dirty slow noisy "
"broken ugly weak annoying mediocre stale cold cramped confusing buggy overpriced "
"tedious lousy sloppy flimsy greasy unpleasant"
)
_NEGATIONS = _words("not never hardly")
_INTENSIFIERS = _words("very really quite extremely truly so rather pretty incredibly fairly")
_OPENERS = (
"honestly",
"overall",
"frankly",
"i think",
"we thought",
"in the end",
"to be honest",
"for me",
"i felt",
"at first",
)
_ENDINGS = ("this time", "for the price", "today", "last night", "on the whole", "as usual")
SENTIMENT_CLASSES = ("negative", "positive")
SENTIMENT_LENGTH = 24
def _clause(rng: random.Random, polarity: int) -> list[str]:
"""``the soup was not very tasty``: a clause whose meaning has ``polarity`` (1 positive,
0 negative). A negation flips the adjective, an intensifier keeps it."""
negated = rng.random() < 0.4
positive_word = polarity == 1 if not negated else polarity == 0
words = [rng.choice(_DETERMINERS), rng.choice(_SUBJECTS), rng.choice(_VERBS)]
if negated:
words.append(rng.choice(_NEGATIONS))
if rng.random() < 0.4:
words.append(rng.choice(_INTENSIFIERS))
words.append(rng.choice(_POSITIVE if positive_word else _NEGATIVE))
return words
def _sentiment(rng: random.Random) -> tuple[list[str], int]:
label = rng.randrange(2)
form = rng.random()
if form < 0.35: # one clause
words = _clause(rng, label)
elif form < 0.55: # two clauses that agree
words = [*_clause(rng, label), "and", *_clause(rng, label)]
else: # "… but …": the second clause decides
words = [*_clause(rng, 1 - label), "but", *_clause(rng, label)]
if rng.random() < 0.3:
words = [*rng.choice(_OPENERS).split(), *words]
if rng.random() < 0.25:
words += rng.choice(_ENDINGS).split()
return words, label
# --------------------------------------------------------------------------- #
# Key lookup: key-value pairs and a question
# --------------------------------------------------------------------------- #
_KEYS = tuple("abcdefghijklmnopqrstuvwxyz")
_VALUES = tuple("0123456789")
_PAIRS = 8
LOOKUP_CLASSES = _VALUES
LOOKUP_LENGTH = _PAIRS + 2
def _lookup(rng: random.Random) -> tuple[list[str], int]:
"""``c7 x2 m4 … ? x``: eight pairs (one token each: a key letter and its digit), then
the question for one of the keys. The answer is its digit."""
keys = rng.sample(_KEYS, _PAIRS)
values = [rng.randrange(len(_VALUES)) for _ in keys]
asked = rng.randrange(_PAIRS)
pairs = [key + _VALUES[value] for key, value in zip(keys, values, strict=True)]
return [*pairs, "?", keys[asked]], values[asked]
# --------------------------------------------------------------------------- #
# Topics: topic words in shared filler words
# --------------------------------------------------------------------------- #
_TOPIC_WORDS = (
_words(
"atom cell energy experiment gene laboratory molecule physics planet research "
"theory chemistry telescope data microscope particle scientist hypothesis "
"electron study biology measurement climate fossil equation"
),
_words(
"match team goal player coach league score football tennis race stadium referee "
"season champion tournament ball sprint medal training fans striker keeper "
"victory defeat penalty"
),
_words(
"recipe oven flour butter garlic onion pan sauce salt pepper bake boil kitchen "
"chef dough spice cheese tomato soup knife roast dinner herbs sugar stew"
),
_words(
"flight hotel passport airport luggage beach map tourist ticket train journey "
"island border guide museum backpack visa coast mountain village cruise station "
"suitcase holiday sightseeing"
),
)
_FILLER = _words(
"the a an and of to in it was we they with on for this that very some new after "
"before really just about when there then our their many few most also more today "
"week year last next people time day good great small big long first other every "
"always often again because while still even almost quite"
)
TOPIC_CLASSES = ("science", "sports", "cooking", "travel")
TOPICS_LENGTH = 64
def _topics(rng: random.Random) -> tuple[list[str], int]:
label = rng.randrange(len(TOPIC_CLASSES))
count = rng.randint(40, TOPICS_LENGTH)
words = []
for _ in range(count):
chance = rng.random()
if chance < 0.2:
words.append(rng.choice(_TOPIC_WORDS[label]))
elif chance < 0.26: # a word of another topic
other = (label + rng.randrange(1, len(TOPIC_CLASSES))) % len(TOPIC_CLASSES)
words.append(rng.choice(_TOPIC_WORDS[other]))
else:
words.append(rng.choice(_FILLER))
return words, label
# --------------------------------------------------------------------------- #
# All datasets
# --------------------------------------------------------------------------- #
def _unique(*groups: object) -> tuple[str, ...]:
words: dict[str, None] = {}
for group in groups:
for item in group: # type: ignore[attr-defined]
for word in str(item).split():
words[word] = None
return (TEXT_PAD, TEXT_UNK, *words)
# id: (sample function, vocabulary, sequence length, class names, seed, train, test)
TEXT_DATASETS = {
"sentiment": (
_sentiment,
_unique(
_DETERMINERS,
_SUBJECTS,
_VERBS,
_NEGATIONS,
_INTENSIFIERS,
_POSITIVE,
_NEGATIVE,
["and", "but"],
_OPENERS,
_ENDINGS,
),
SENTIMENT_LENGTH,
SENTIMENT_CLASSES,
20_261_117,
6000,
1000,
),
"lookup": (
_lookup,
_unique([key + value for key in _KEYS for value in _VALUES], ["?"], _KEYS),
LOOKUP_LENGTH,
LOOKUP_CLASSES,
20_261_118,
12_000,
2000,
),
"topics": (
_topics,
_unique(_FILLER, *_TOPIC_WORDS),
TOPICS_LENGTH,
TOPIC_CLASSES,
20_261_119,
3000,
1000,
),
}
def text_vocabulary(dataset: str) -> tuple[str, ...]:
"""The words of ``dataset`` in the order of their ids (0 ``<pad>``, 1 ``<unk>``)."""
return TEXT_DATASETS[dataset][1]
def text_sample(dataset: str, index: int) -> tuple[list[str], int]:
"""The words of sample ``index`` (before padding) and its class."""
make, *_, seed, _train, _test = TEXT_DATASETS[dataset]
return make(random.Random(seed * 100_003 + index))
def tokenize(text: str) -> list[str]:
"""Lower-case words, numbers and single punctuation marks: "Not bad!" -> not, bad, !."""
return re.findall(r"[a-z0-9']+|[^\sa-z0-9']", text.lower())
def encode(words: list[str], vocabulary: tuple[str, ...], length: int) -> list[int]:
"""Token ids of ``words`` (unknown words get the id of ``<unk>``), cut or padded with
``<pad>`` to ``length``."""
index = {word: i for i, word in enumerate(vocabulary)}
ids = [index.get(word, 1) for word in words[:length]]
return ids + [0] * (length - len(ids))
def decode(ids: list[int], vocabulary: tuple[str, ...]) -> list[str]:
"""The words of token ids, without the padding."""
return [vocabulary[i] if 0 <= i < len(vocabulary) else TEXT_UNK for i in ids if i != 0]
def text_examples(dataset: str, count: int = 2) -> list[dict[str, str]]:
"""The first samples of the test split as text with their class (for the data picker)."""
*_, classes, _seed, train, _test = TEXT_DATASETS[dataset]
examples = []
for index in range(train, train + count):
words, label = text_sample(dataset, index)
examples.append({"text": " ".join(words), "class": classes[label]})
return examples
def text_dataset(dataset: str, start: int, count: int) -> tuple[list[list[int]], list[int]]:
"""Samples ``start`` … ``start + count - 1`` as token ids (padded) and classes. The
first ``train`` samples are the training split, the next ``test`` the test split."""
_, vocabulary, length, *_ = TEXT_DATASETS[dataset]
index = {word: i for i, word in enumerate(vocabulary)}
ids, labels = [], []
for number in range(start, start + count):
words, label = text_sample(dataset, number)
row = [index[word] for word in words[:length]]
ids.append(row + [0] * (length - len(row)))
labels.append(label)
return ids, labels
# --------------------------------------------------------------------------- #
# Training on the built-in text dataset, and predictions for new texts
# --------------------------------------------------------------------------- #
DATASET = "topics" # the built-in text dataset (see TEXT_DATASETS above)
NUM_CLASSES = 4
def load_dataset() -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""The token ids and classes of the training texts and of the test texts."""
*_, train_size, test_size = TEXT_DATASETS[DATASET]
ids, labels = text_dataset(DATASET, 0, train_size + test_size)
x, y = torch.tensor(ids), torch.tensor(labels)
return x[:train_size], y[:train_size], x[train_size:], y[train_size:]
def evaluate(model: nn.Module, loader: DataLoader, loss_fn, device: str) -> tuple[float, float]:
"""The mean loss and the accuracy on the texts of ``loader``."""
model.eval()
total, correct, seen = 0.0, 0, 0
with torch.no_grad():
for inputs, targets in loader:
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
total += loss_fn(outputs, targets).item() * len(inputs)
correct += (outputs.argmax(dim=1) == targets).sum().item()
seen += len(inputs)
return total / max(seen, 1), correct / max(seen, 1)
def train(
model: nn.Module,
epochs: int,
batch_size: int,
lr: float,
seed: int,
run: BrickDNNRun | None = None,
) -> None:
"""Train on 80 % of the training texts (the split depends only on ``seed``), validate
on the rest after every epoch and measure the test texts once at the end."""
x, y, test_x, test_y = load_dataset()
generator = torch.Generator().manual_seed(seed)
order = torch.randperm(len(x), generator=generator)
n_val = len(x) // 5
val_rows, train_rows = order[:n_val], order[n_val:]
train_y = y[train_rows]
train_loader = DataLoader(
TensorDataset(x[train_rows], train_y),
batch_size=batch_size,
shuffle=True,
generator=generator,
)
val_loader = DataLoader(TensorDataset(x[val_rows], y[val_rows]), batch_size=256)
test_loader = DataLoader(TensorDataset(test_x, test_y), batch_size=256)
if torch.cuda.is_available():
device = "cuda"
elif torch.backends.mps.is_available():
device = "mps"
else:
device = "cpu"
print(
f"Training on {device}: {len(train_rows)} texts of {DATASET}, {n_val} for validation, "
f"{len(test_x)} for the test"
)
model.to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
summary: dict[str, float] = {}
for epoch in range(1, epochs + 1):
model.train()
train_loss, seen = 0.0, 0
for inputs, targets in train_loader:
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
loss = loss_fn(model(inputs), targets)
loss.backward()
optimizer.step()
train_loss += loss.item() * len(inputs)
seen += len(inputs)
val_loss, val_accuracy = evaluate(model, val_loader, loss_fn, device)
print(
f"Epoch {epoch:3d}/{epochs} train loss {train_loss / max(seen, 1):.4f}"
f" val loss {val_loss:.4f} val acc {val_accuracy:.1%}"
)
summary = {
"train_loss": train_loss / max(seen, 1),
"val_loss": val_loss,
"val_accuracy": val_accuracy,
}
if run is not None:
run.log(epoch=epoch, **summary)
test_loss, test_accuracy = evaluate(model, test_loader, loss_fn, device)
print(f"Test accuracy: {test_accuracy:.1%}")
if run is not None:
summary.update(test_loss=test_loss, test_accuracy=test_accuracy)
run.finish(summary=summary)
model.cpu()
def save_model(model: nn.Module, path: str) -> None:
"""Save the weights together with what predict_text() needs to read new texts."""
_, vocabulary, length, class_names, *_ = TEXT_DATASETS[DATASET]
preprocessing = {
"dataset": DATASET,
"vocabulary": list(vocabulary), # token id i is vocabulary[i]
"length": length, # texts are cut or padded to this many tokens
"class_names": list(class_names),
}
torch.save({"state_dict": model.state_dict(), "preprocessing": preprocessing}, path)
print(f"Saved the weights and the vocabulary to {path}")
def predict_text(model: nn.Module, path: str, text: str) -> None:
"""Print the class of a text and the probability of every class."""
checkpoint = torch.load(path, map_location="cpu", weights_only=True)
model.load_state_dict(checkpoint["state_dict"])
model.eval()
preprocessing = checkpoint["preprocessing"]
vocabulary = tuple(preprocessing["vocabulary"])
ids = encode(tokenize(text), vocabulary, preprocessing["length"])
print("Tokens:", " ".join(decode(ids, vocabulary)))
with torch.no_grad():
probabilities = model(torch.tensor([ids])).softmax(dim=1)[0]
names = preprocessing["class_names"]
for index in probabilities.argsort(descending=True).tolist():
name = names[index] if index < len(names) else f"class {index}"
print(f"{name}: {probabilities[index].item():.1%}")
# --------------------------------------------------------------------------- #
# Logging to Brick DNN, only with the environment variable BRICKDNN_TOKEN
# --------------------------------------------------------------------------- #
# The server and the saved network the runs belong to (BRICKDNN_URL and BRICKDNN_PROJECT
# override them). The token is never stored here: it is read from BRICKDNN_TOKEN.
BRICKDNN_URL = "https://brickdnn.com"
BRICKDNN_PROJECT = None
class BrickDNNRun:
"""A run logged to Brick DNN (see brickdnn/tracking.py), or an inert one without the
environment variable BRICKDNN_TOKEN."""
# Points are sent in batches: when this many are waiting, or after INTERVAL seconds.
BATCH = 200
INTERVAL = 2.0
# Points kept while the server cannot be reached; failures in a row before giving up.
BUFFER = 1000
ATTEMPTS = 3
RETRY_SECONDS = 10.0
TIMEOUT = 5.0
def __init__(self, url: str | None = None, token: str | None = None) -> None:
url = os.environ.get("BRICKDNN_URL") or url or "https://brickdnn.com"
self.url = url.strip().rstrip("/")
self.token = (token if token is not None else os.environ.get("BRICKDNN_TOKEN", "")).strip()
self.id: str | None = None
self.active = bool(self.token)
self.points: list[dict] = []
self._create: dict = {}
self._started = time.monotonic()
self._sent = self._started # the first batch waits INTERVAL too
self._failures = 0
self._retry_at = 0.0
self._warned = False
@classmethod
def start(
cls,
name: str | None = None,
config: dict | None = None,
project: int | None = None,
dataset: str | None = None,
task: str | None = None,
epochs: int | None = None,
url: str | None = None,
token: str | None = None,
) -> BrickDNNRun:
"""Create the run on the server (nothing happens without a token)."""
run = cls(url, token)
if not run.active:
return run
if os.environ.get("BRICKDNN_PROJECT", "").strip().isdigit():
project = int(os.environ["BRICKDNN_PROJECT"].strip())
body = {
"name": os.environ.get("BRICKDNN_RUN_NAME") or name,
"config": config or {},
"project": project,
"dataset": dataset,
"task": task,
"epochs": epochs,
"client": "brickdnn-tracking/1",
}
run._create = {key: value for key, value in body.items() if value is not None}
run._open()
return run
def _open(self) -> bool:
"""Create the run on the server if that has not worked yet."""
if self.id is None and self.active and time.monotonic() >= self._retry_at:
answer = self._send("POST", "/api/tracking/runs/", self._create)
if isinstance(answer, dict) and isinstance(answer.get("id"), str):
self.id = answer["id"]
print(f"Brick DNN: logging this run to {self.url}/runs", file=sys.stderr)
return self.id is not None
def log(self, epoch: int | None = None, step: int | None = None, **metrics) -> None:
"""One point of the curves: ``epoch`` (or ``step``) and numbers such as
``train_loss``, ``val_loss`` or ``val_accuracy``; other values are left out."""
if not self.active:
return
try:
point: dict = {"time": round(time.monotonic() - self._started, 3)}
if epoch is not None:
point["epoch"] = int(epoch)
if step is not None:
point["step"] = int(step)
for key, value in metrics.items():
number = self._number(value)
if number is not None:
point[str(key)] = number
self.points.append(point)
del self.points[: max(0, len(self.points) - self.BUFFER)]
if len(self.points) >= self.BATCH or time.monotonic() - self._sent >= self.INTERVAL:
self.flush()
except Exception as error: # logging never stops the training
self._fail(error)
def flush(self) -> None:
"""Send the points that wait."""
if not self.active or not self.points or time.monotonic() < self._retry_at:
return
if not self._open():
return
while self.active and self.points:
batch = self.points[: self.BATCH]
if self._send("POST", f"/api/tracking/runs/{self.id}/log/", {"points": batch}) is None:
return
del self.points[: len(batch)]
self._sent = time.monotonic()
def finish(
self, status: str = "completed", summary: dict | None = None, message: str | None = None
) -> None:
"""End the run: ``completed``, ``failed`` or ``stopped``, with its final numbers
(e.g. ``{"test_accuracy": 0.93}``)."""
if not self.active:
return
try:
self._retry_at = 0.0
self.flush()
if self.active and self._open():
numbers = {str(k): self._number(v) for k, v in (summary or {}).items()}
body: dict = {
"status": status,
"summary": {k: v for k, v in numbers.items() if v is not None},
}
if message:
body["message"] = str(message)[:500]
self._send("POST", f"/api/tracking/runs/{self.id}/finish/", body)
except Exception as error:
self._fail(error)
self.active = False
def __enter__(self) -> BrickDNNRun:
return self
def __exit__(self, kind, error, traceback) -> bool:
if kind is None:
self.finish("completed")
elif issubclass(kind, KeyboardInterrupt):
self.finish("stopped", message="Stopped with Ctrl+C.")
else:
self.finish("failed", message=f"{kind.__name__}: {error}")
return False # an error goes on as before
@staticmethod
def _number(value) -> float | int | None:
try:
if hasattr(value, "item"):
value = value.item() # a tensor or a NumPy number
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
return value if math.isfinite(value) else None
except Exception:
return None
def _send(self, method: str, path: str, body: dict) -> dict | None:
"""The server's answer, or None if the request failed (warned once)."""
try:
request = urllib.request.Request(
self.url + path,
data=json.dumps(body).encode(),
method=method,
headers={
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
"User-Agent": "brickdnn-tracking/1",
},
)
with urllib.request.urlopen(request, timeout=self.TIMEOUT) as response:
answer = json.loads(response.read().decode() or "{}")
self._failures = 0
return answer if isinstance(answer, dict) else {}
except urllib.error.HTTPError as error:
# Busy or broken for a moment: again later. Refused (token, limit, the run was
# stopped in the app): for good.
self._fail(error, final=error.code not in (408, 429) and error.code < 500)
except Exception as error:
self._fail(error)
return None
def _fail(self, error: Exception, final: bool = False) -> None:
self._failures += 1
if not self._warned:
self._warned = True
detail = str(error)
if isinstance(error, urllib.error.HTTPError):
try:
detail = json.loads(error.read().decode()).get("detail") or detail
except Exception:
detail = f"HTTP {error.code}"
print(
f"Brick DNN: could not log to {self.url} ({detail}). The training goes on"
+ ("." if final else "; logging is tried again a few times."),
file=sys.stderr,
)
if final or self._failures >= self.ATTEMPTS:
self.active = False
self.points = []
else:
self._retry_at = time.monotonic() + self.RETRY_SECONDS
def main() -> None:
parser = argparse.ArgumentParser(description="NeuralNetwork generated with Brick DNN")
parser.add_argument(
"--train", action="store_true", help=f"train on the built-in dataset {DATASET}"
)
parser.add_argument("--predict", metavar="TEXT", help="classify this text")
parser.add_argument("--epochs", type=int, default=10)
parser.add_argument("--batch-size", type=int, default=64)
parser.add_argument("--lr", type=float, default=1e-3, help="learning rate")
parser.add_argument("--seed", type=int, default=0, help="for a repeatable run")
parser.add_argument(
"--save",
default="model.pt",
help="the trained model (--train writes it, --predict reads it)",
)
args = parser.parse_args()
torch.manual_seed(args.seed) # the same initial weights for the same seed
model = NeuralNetwork()
if args.predict:
predict_text(model, args.save, args.predict)
return
print(model)
print(f"Trainable parameters: {count_parameters(model):,}")
if args.train:
# Logged to Brick DNN only with the environment variable BRICKDNN_TOKEN.
with BrickDNNRun.start(
name="NeuralNetwork",
config={
"epochs": args.epochs,
"batch_size": args.batch_size,
"learning_rate": args.lr,
"optimizer": "adam",
"seed": args.seed,
"loss": "cross_entropy",
"val_split": 0.2,
},
project=BRICKDNN_PROJECT,
dataset="Topics",
task="classification",
epochs=args.epochs,
url=BRICKDNN_URL,
) as run:
train(model, args.epochs, args.batch_size, args.lr, args.seed, run)
save_model(model, args.save)
return
# Check the model with a random batch of 2 samples.
model.eval()
x = torch.randint(0, 10000, (2, 64,))
with torch.no_grad():
out = model(x)
print("Output shape:", tuple(out.shape)) # expected (2, 4)
if __name__ == "__main__":
main()