39.10  API-Referenz für d2l

Dieser Abschnitt führt die Klassen und Funktionen des Pakets d2l in alphabetischer Reihenfolge auf. Jeder Eintrag verweist auf die Stelle im Buch, an der die jeweilige Klasse oder Funktion definiert und erläutert wird. Die generierten Module sind auch im GitHub-Repository des Buchs verfügbar.

39.10.1 Klassen

class APIRecording

APIRecording(mode, record_dir, cost_cap_usd, providers)

The caches, the listing and the shared cost cap of one recording. In ?sec-lm-api

  • folder(key) — The folder of one artifact (see the class docstring).
  • cache(key, arm) — The JSONL cache file of one arm of an artifact.
  • snapshot_listing(models, weights, key='lm-api-listing-v1') — The router listing of this recording, from <folder of key>/
  • hosted(model, cache, share, **kwargs) — A d2l.openrouter_api client of model at its pinned provider that
  • add(api) — Keep a client for the manifest; returns it.

class Accumulator

Accumulator(n)

For accumulating sums over n variables. Abschnitt 39.9

  • add(*args)
  • reset()

class ActorCritic(d2l.Policy)

ActorCritic(policy, value, lr=0.01)

A policy and a value function, each with its own optimizer. Abschnitt 14.9

  • V(obs) — V(s) for a batch of states, as a tensor.
  • value_np(obs) — V(s) for a numpy batch of states, as numpy.
  • tabular(num_states, num_actions, lr=0.1, seed=None) — Preference and value tables: two zero-initialized embeddings.
  • mlp(obs_dim, num_actions, hidden=64, lr=0.01, seed=None) — The same container with the tables replaced by one-hidden-layer nets. Abschnitt 14.9

class AdjointScan(torch.autograd.Function)

linear_scan whose backward pass is a second scan, run backward. Abschnitt 12.5

  • forward(ctx, a, b)
  • backward(ctx, grad_h)

class Animator

Animator(xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1, figsize=(3.5, 2.5))

For plotting data in animation. Abschnitt 39.9

  • add(x, y)

class ArrayData(d2l.DataModule)

ArrayData(X, y, batch_size=64)

Minibatches of the arrays X and y; training batches are shuffled. Abschnitt 4.5

  • get_dataloader(train)

class AttentionMixer(d2l.CausalAttention)

AttentionMixer(num_hiddens, num_heads, conv_width=None, rope=True)

Causal multi-head attention, with rotary positions unless rope is Abschnitt 12.1.4

  • qkv(X, offset=0, tables=None)

class Autoencoder(nn.Module)

Autoencoder(latent_channels=4, ch=64, num_blocks=2)

Residual convolutional autoencoder from 28x28x1 images to a 7x7 Abschnitt 17.7

  • encode(x)
  • forward(x)

class Averager

Example-weighted means of batch metrics, summed on the device. Abschnitt 2.4

  • add(metrics, n)
  • mean() — One host synchronization per metric; the loss comes first.

class BM25Index

BM25Index(docs_tokens, k1=1.2, b=0.75, idf='lucene')

BM25 over tokenized documents: W[t, d] = idf(t) tf / (tf + k1 (1 - b ?sec-lm-retrieval

  • scores(query_tokens) — BM25 score of every document (a repeated token counts twice).
  • search(query_tokens, k) — Indices and scores of the k best documents, best first.

class BPETokenizer

BPETokenizer(vocab_size=1024, pattern=None, specials=('<pad>', '<bos>', '<eos>'))

Byte-level BPE tokenizer trained by iterated most-frequent-pair Abschnitt 8.2

  • pad()
  • bos()
  • eos()
  • train(text) — Learn vocab_size - 256 merges, most frequent pair first. Abschnitt 8.2
  • encode(text, allow_special=False)
  • decode(ids)
  • from_tiktoken(name) — Load a published bytes->rank table (e.g. ‘gpt2’) into our encoder. Abschnitt 8.2
  • to_tokens(ids)

class BackgroundLoad

BackgroundLoad(api, request, lanes, warmup=2.0)

An async context manager that keeps lanes requests in flight ?sec-lm-api

class BananasDataset(torch.utils.data.Dataset)

BananasDataset(is_train)

A customized dataset to load the banana detection dataset. ?sec-object-detection-dataset

class Batch

Batch(obs, act, rew, next_obs, term, ep_ends)

A flat batch of transitions, plus the episode boundaries. Abschnitt 14.7

  • episodes() — Yield one slice per episode.
  • episode_returns(gamma=1.0) — R(tau), the discounted return, one number per episode.
  • per_step(values) — Repeat one value per episode over that episode’s steps.
  • backward_scan(x, factor) — y_t = x_t + factor * y_{t+1}, restarted at every episode boundary. Abschnitt 14.8
  • reward_to_go(gamma) — G_t: the discounted return of the rest of its episode, by one scan. Abschnitt 14.8
  • truncation_bootstrap(gamma, V) — gamma^(T-t) (1 - term_T) V(s_T) for every step t of each episode: Abschnitt 14.9
  • td_target(bootstrap, gamma) — r_t + gamma (1 - terminated) V(s’), by a numpy bootstrap. Abschnitt 15.1
  • gae(value_fn, gamma, lam) — GAE(gamma, lam): the reward-to-go scan, run on the TD errors. Abschnitt 15.1
  • lambda_return(value_fn, gamma, lam) — The critic’s target for GAE: the advantage plus the value it is Abschnitt 15.1

class Benchmark

Benchmark(f, warmup=3, repeats=10, desc='time', devices=None)

Time a callable: warmup, then device-synchronized average seconds. Abschnitt 5.7

class BookCorpus

BookCorpus(manifest, docs, chunks, tag)

The book corpus under one chunking: chunks (a list of dicts in ?sec-lm-retrieval

  • header(chunk) — ‘Chapter > Section > Subsection’ of a chunk.
  • texts(view='display', header=True) — Chunk texts, in chunk order, for a view: ‘display’ (the text),
  • split_of(doc_id) — ‘train’, ‘dev’ or ‘test’ of a document.
  • chunk_split(chunk_id) — The split of the document a chunk comes from.
  • span_to_chunk_ids(doc_id, start, end, min_overlap=0.5) — Ids of the chunks of doc_id that overlap the character span

class BookRetriever

BookRetriever(corpus=None, dense=DEFAULT_EMBEDDER, index='flat', reranker=None, fusion='rrf', rrf_k=60, device=None, cache=True, bm25_params=None)

Hybrid retrieval over the book corpus: BM25 over the ‘sparse’ view ?sec-lm-retrieval

  • chunk_vectors() — Unit vectors of the chunks (N, m), float16: the registered set
  • search_batch(queries, k=10, mode='hybrid', rerank_k=None) — search for each of several queries.
  • search(query, k=10, mode='hybrid', rerank_k=None) — The k best chunks for query as a list of Hit, best first; with
  • release() — Free the GPU models (query encoder, reranker); a later search

class CausalAttention(nn.Module)

CausalAttention(num_hiddens, num_heads, bias=False, rope=False, num_kv_heads=None)

Fused causal self-attention, optionally rotary; num_kv_heads < Abschnitt 11.2

  • qkv(X, offset=0, tables=None) — Queries, keys, and values of X, each (batch, heads, length, head
  • forward(X, keys=None, values=None, mask=None, tables=None)

class ChatAPI

ChatAPI(base_url, model, api_key=None, cache=None, mode='replay', price=None, cost_cap_usd=None, timeout=120.0, max_retries=6, default_params=None, http_client=None)

A measuring and replaying client for OpenAI-compatible chat ?sec-lm-api

  • spent_usd() — USD settled by this client’s live calls in this session.
  • entries(request_hash) — The cache entries (dicts) recorded for one request hash.
  • chat(messages, replica=0, stream=False, **params) — Synchronous d2l.ChatAPI.achat, run on the client’s private event
  • models() — The model ids the endpoint lists (GET /models; never replayed).
  • manifest() — This session’s counts (calls, cache hits, live calls, HTTP

class Classifier(d2l.Module)

The base class of classification models. Abschnitt 3.3

  • validation_step(batch)
  • accuracy(Y_hat, Y, averaged=True) — Compute the fraction of correct predictions. Abschnitt 3.3
  • loss(Y_hat, Y, averaged=True)
  • layer_summary(X_shape)

class CorpusManifest

CorpusManifest(name, sources=None, stages=None, tokenizer=None, format=None, splits=None)

The provenance of a corpus (schema d2l-corpus/1): its sources, the ?sec-lm-crawl

  • add_source(id, uri, revision=None, license=None, n_docs=None, bytes=None, **extra)
  • add_stage(name, params, n_in, n_out, drops, in_hash, out_hash, impl=None, version=None, tokens_out=None)
  • to_dict()
  • canonical_json()
  • sha256()
  • save(path) — Write the canonical JSON, so the file’s SHA-256 is sha256().
  • load(path)
  • to_card() — A Markdown dataset card generated from the manifest alone.

class CostCapExceeded(RuntimeError)

A live call whose worst-case cost would cross the client’s cost cap; ?sec-lm-api

class DataModule(d2l.HyperParameters)

DataModule(root='../data', num_workers=4)

The base class of data. Abschnitt 2.4

  • get_dataloader(train)
  • train_dataloader()
  • val_dataloader()
  • get_tensorloader(tensors, train, indices=slice(0, None))

class DiT(nn.Module)

DiT(img_size=28, patch_size=4, num_channels=1, width=256, depth=6, num_heads=4, num_classes=None)

Diffusion transformer conditioned on a time t in [0, 1] and, with Abschnitt 17.7

  • forward(x, t, y=None)

class DiTBlock(d2l.ViTBlock)

DiTBlock(num_hiddens, mlp_num_hiddens, num_heads)

ViTBlock with adaLN-Zero: the condition c sets a shift, a scale and a Abschnitt 17.7

  • forward(X, c)

class Discriminator(nn.Module)

Discriminator(resolution, base_ch)

Critic that mirrors the generator: conv + leaky ReLU + bilinear Abschnitt 16.5

  • phi(x)
  • forward(x)

class DocList(list)

A list of Doc with the rows that failed to rebuild in .mismatches. ?sec-lm-crawl

class DotProductAttention(nn.Module)

DotProductAttention(dropout=0.0)

Scaled dot-product attention over the last two axes. Abschnitt 10.2

  • forward(queries, keys, values, mask=None)

class EMA

EMA(model, half_life)

Exponential moving average of a model’s parameters, given as a Abschnitt 16.5

  • update(model)

class EvalResult

EvalResult(per_item, meta)

Per-item results of one model on one suite (per_item: task, item_id, ?sec-lm-eval-suites

  • scores(task=None) — One task’s scores ordered by item id, or a dict over tasks. Ids
  • summary(n_boot=2000) — Per task: n, mean and its 95% interval (clusters resampled).
  • compare(other, n_boot=10000, seed=0) — Per task, paired_bootstrap of this model’s scores minus other’s,
  • save(path) — Write per_item to path (parquet, rows sorted) and meta, without the ?sec-lm-eval-suites
  • load(path) — An EvalResult written by save. ?sec-lm-eval-suites

class EvalSuite

EvalSuite(tasks, name='suite', batch_size=8, n=None, seed=0)

Evaluation tasks (EvalTask records, or ids of d2l.EVAL_TASKS) with ?sec-lm-eval-suites

  • hash() — sha256 of the canonical JSON of every task’s fields, followed by
  • items(task_id) — The items of one task in subset order: dicts with the item’s
  • run(model, tokenizer, seed=0, cache_dir=None, rerun=False, sandbox=False) — Score every item and return an EvalResult. With cache_dir, results ?sec-lm-eval-suites
  • from_manifest(name_or_path, batch_size=8) — The suite of a frozen manifest: a name in d2l.EVAL_SUITES or a JSON ?sec-lm-eval-suites
  • to_manifest(path=None) — The suite as a JSON-ready manifest {‘name’, ‘tasks’}; with path, ?sec-lm-eval-suites

class FakeChatServer

FakeChatServer(service_time, capacity, fail_rate=0.0, rate_limit=None, script=None, seed=0)

An in-process chat-completions server for tests. Each request takes ?sec-lm-api

  • transport() — An httpx.AsyncBaseTransport of the flavour the SDK uses.

class FashionCNN(nn.Module)

A compact CNN for Fashion-MNIST: two conv-pool stages, two linear. Abschnitt 9.5

  • forward(X)

class FashionMNIST(d2l.DataModule)

FashionMNIST(batch_size=64, resize=(28, 28))

The Fashion-MNIST dataset. Abschnitt 3.2

  • text_labels(indices) — Return text labels. Abschnitt 3.2
  • get_dataloader(train)
  • batchify(examples) — Stack examples into a minibatch, scale to [0, 1], resize if asked. Abschnitt 3.2
  • visualize(batch, nrows=1, ncols=8, labels=None) — Show the images of a batch in grayscale, titled by their labels. Abschnitt 3.2

class FeatureCNN(nn.Module)

FeatureCNN(feature_dim=128, resolution=32)

Three conv blocks, global average pooling, and a linear head. Inputs Abschnitt 39.9

  • features(x)
  • forward(x)

class FeedForward(nn.Module)

FeedForward(num_hiddens, act='swiglu', bias=False)

Position-wise FFN: GELU MLP or SwiGLU at matched parameter count. Abschnitt 11.1

  • forward(X)

class GPT(nn.Module)

GPT(vocab_size, num_hiddens=256, num_heads=8, num_blks=6, max_len=1024, pos='rope', norm='rms', act='swiglu', pre_norm=True, bias=False, dropout=0, num_kv_heads=None, ffn_factory=None)

Decoder-only transformer language model built from configurable Abschnitt 11.2

  • forward(X)
  • init_weights() — GPT-2’s initialization of the linear layers: N(0, 0.02^2) weights and Abschnitt 11.2
  • generate(prefix, num_tokens, temperature=1.0, top_k=None) — Sample a continuation of the token-id list prefix. Abschnitt 11.2

class GatedDeltaNet(d2l.GatedLinearAttention)

GatedDeltaNet(num_hiddens, num_heads, chunk_size=32, conv_width=4, timescales=(4, 256))

Gated linear attention whose memory is written by the delta rule. Abschnitt 12.7

  • memory(X, Q, K, V, log_a)

class GatedLinearAttention(nn.Module)

GatedLinearAttention(num_hiddens, num_heads, chunk_size=16, conv_width=4, timescales=(4, 256))

Multi-head linear attention with one input-dependent decay per head. Abschnitt 12.6

  • init_decays(tau_min, tau_max) — Start the decays at exp(-1/tau), tau log-uniform in range.
  • decays(X) — Log decays, (batch_size * num_heads, T). Abschnitt 12.6
  • memory(X, Q, K, V, log_a) — Outputs of the decayed matrix memory of every head. X is unused here; Abschnitt 12.6
  • forward(X)

class GaussianHead(nn.Module)

GaussianHead(obs_dim, act_dim, hidden, state_std=False, trunk=None, zero_mean=False)

A Gaussian over actions: a trunk of hidden features, a linear mean, Abschnitt 14.9

  • forward(obs)

class GaussianMixture

GaussianMixture(means, weights, std, device=None)

A mixture of isotropic Gaussians, exact at every noise level. Abschnitt 17.1

  • three_modes(device=None) — The chapter’s running example, with mode weights 0.5/0.3/0.2.
  • sample(n) — n draws from the mixture.
  • log_prob(x, alpha=1.0, sigma=0.0) — log p(x) for x = alpha x0 + sigma eps.
  • score(x, alpha=1.0, sigma=0.0) — The gradient of log p(x) for x = alpha x0 + sigma eps.
  • posterior_mean(x, alpha, sigma) — E[x0 | x]; finite at alpha = 0 and at sigma = 0.
  • nll(x) — Mean negative log-likelihood of clean points, in nats. Abschnitt 17.1
  • summary(x) — Mode weights by nearest mean, stray fraction, spread of the rest. Abschnitt 17.1
  • velocity(x, t) — E[eps - x0 | x_t] on the linear path x_t = (1 - t) x0 + t eps. Abschnitt 17.2

class GaussianPath

GaussianPath(alpha, sigma)

x_t = alpha(t) x0 + sigma(t) eps, data at t = 0 and noise at t = 1. Abschnitt 17.2

  • vp(beta_min=0.1, beta_max=20.0) — Variance preserving, Ho et al.’s linear beta in continuous time.
  • linear() — The straight line of flow matching and rectified flow.
  • cosine(s=0.008) — Variance preserving, Nichol and Dhariwal’s cosine schedule.
  • log_snr(t) — lambda_t = log(alpha_t^2 / sigma_t^2), falling from +inf at 0.
  • sample(x0, t, eps) — x_t for per-example times t of shape (n,).
  • grid(steps, t_start=1.0, t_end=0.0) — Lists of alpha and sigma at steps + 1 even times, t_start to t_end. Abschnitt 17.2
  • rates(t) — The time derivatives (alpha’(t), sigma’(t)), by forward-mode AD. Abschnitt 17.2
  • target(kind, x0, eps, t) — The regression target of a kind: eps, x0, v, score or velocity. Abschnitt 17.2
  • x0_eps(kind, out, x, t) — The (x0, eps) that a prediction out of a kind implies at (x, t). Abschnitt 17.2
  • sigma_bars(steps) — sigma_bar = sigma / alpha on the grid of steps; inf where alpha = 0. Abschnitt 17.3
  • time_at(log_snr) — The time with a given log-SNR, by bisection (lambda_t falls in t). Abschnitt 17.3

class GaussianPolicy(ActorCritic)

GaussianPolicy(obs_dim, act_dim, hidden=64, lr=0.01, seed=None, **head_args)

The same interface over a Normal instead of a softmax; nothing that Abschnitt 14.9

  • log_prob(obs, act) — log pi(a|s): the Normal density, summed over action dimensions.
  • act(obs, rng) — Sample mu(s) + sigma(s) z, z ~ N(0, I) from the numpy rng.
  • act_greedy(obs, rng=None) — The mean action mu(s).

class Generator(nn.Module)

Generator(latent_dim, resolution, base_ch, extra_ch=0, const_ch=128)

Learned 4x4 constant + projected latent (+ extra 4x4 input maps), Abschnitt 16.5

  • forward(z, extra=None)

class HashedBagClassifier(nn.Module)

HashedBagClassifier(num_buckets=2 ** 20, dim=64, ngrams=(1, 2), num_outputs=1)

fastText’s classifier: word n-grams of the lower-cased, ?sec-lm-quality-filtering

  • hash_ids(text)
  • featurize(texts) — (ids, offsets) of a batch of texts for nn.EmbeddingBag.
  • forward(ids, offsets)

class HyperParameters

The base class of hyperparameters. Abschnitt 39.9

  • save_hyperparameters(ignore=None) — Save function arguments into instance attributes. Abschnitt 39.9

class IVFIndex

IVFIndex(nlist, nprobe=1)

Inverted file index: the k-means cells of the training vectors; a ?sec-lm-retrieval

  • train(X, n_iter=20, seed=0)
  • add(X) — Store the rows of X (ids 0, 1, …) grouped by cell.
  • search(Q, k) — (distances, ids) of the k nearest stored rows per query, nearest

class LMOptimizer

LMOptimizer(model, lr, num_steps, warmup, weight_decay=0.1, max_norm=1.0)

AdamW with weight decay on the weight matrices only, a linear warmup Abschnitt 11.2

  • zero_grad()
  • step()

class LeNet(d2l.Classifier)

LeNet(lr=0.1, num_classes=10)

The layout of LeNet-5, with sigmoid activations and average pooling. Abschnitt 6.6

  • weight_init(module)

class LinearRegression(d2l.Module)

LinearRegression(lr)

Linear regression built from framework components. Abschnitt 2.5

  • weight_init(module)
  • loss(y_hat, y)
  • configure_optimizers()
  • get_w_b()

class LinearRegressionScratch(d2l.Module)

LinearRegressionScratch(num_inputs, lr, sigma=0.01)

The linear regression model implemented from scratch. Abschnitt 2.4

  • forward(X)
  • loss(y_hat, y)
  • configure_optimizers()

class LocalChatServer

LocalChatServer(cmd, port=None, host='127.0.0.1', ready_timeout=900.0)

An OpenAI-compatible server (such as transformers serve) run as a ?sec-lm-api

  • start()
  • stop()

class Mamba(nn.Module)

Mamba(num_hiddens, num_states=16, expand=2, conv_width=4, **ssm_args)

The Mamba layer: a gated selective SSM between two projections. Abschnitt 12.5

  • ssm_input(X) — The input of the SSM and the gate branch.
  • forward(X)

class MaskedSoftmaxCELoss(nn.CrossEntropyLoss)

The softmax cross-entropy loss with masks. Abschnitt 39.9

  • forward(pred, label, valid_len)

class MinGRU(nn.Module)

MinGRU(num_inputs, num_hiddens)

The minimal GRU: its gate and candidate read only the input. Abschnitt 12.3

  • coefficients(X) — Decays a_t and writes b_t of the linear recurrence.
  • forward(X)

class MixtureGenerator(nn.Module)

MixtureGenerator(mu, A)

x = mu_k + z A_k for a uniformly drawn component k. Abschnitt 16.2

  • forward(z, k)
  • params_np()

class Module(nn.Module, d2l.HyperParameters)

The base class of models. Abschnitt 2.4

  • loss(y_hat, y)
  • forward(X)
  • training_step(batch) — The mean loss on one minibatch, or a dict of batch-mean metrics
  • validation_step(batch) — The mean loss on one minibatch of validation data, or a dict of
  • configure_optimizers()
  • apply_init(inputs, init=None) — Run a dry pass to fix lazy shapes, then apply init. Abschnitt 5.1.4

class MultiHeadAttention(nn.Module)

MultiHeadAttention(num_hiddens, num_heads, dropout=0.0, bias=False, num_kv_heads=None)

Multi-head attention with heads as an explicit axis; num_kv_heads < Abschnitt 10.3

  • forward(queries, keys, values, mask=None)
  • attention_weights() — Weights of the last call: (batch, num_heads, queries, keys).
  • split_heads(X, num_heads) — (batch, length, num_heads * width) -> (batch, num_heads, length, Abschnitt 10.3
  • merge_heads(X) — Reverse split_heads: (batch, num_heads, length, width) -> (batch, Abschnitt 10.3

class NgramIndex

NgramIndex(n=13)

Hashed word n-grams of indexed texts, for decontamination: a key is ?sec-lm-dedup

  • add(text, tag)
  • query(text) — [(tag, number of the text’s distinct n-grams in tag’s text)],

class PatchEmbedding(nn.Module)

PatchEmbedding(img_size=96, patch_size=16, num_hiddens=512, num_channels=3)

Image-to-sequence stem of the vision transformer. Abschnitt 11.5

  • forward(X)

class Policy(nn.Module)

Policy(policy, lr=0.01)

A policy network and its optimizer; pi(.|s) is the softmax of the Abschnitt 14.5

  • log_prob(obs, act) — log pi(a|s) for a batch of states and the actions taken there.
  • tabular(num_states, num_actions, lr=0.1, seed=None) — One preference theta_{s,a} per state-action pair: an embedding.
  • act(obs, rng) — Sample an action; numpy in, int out, the acting protocol of evaluate. Abschnitt 14.5
  • act_greedy(obs, rng=None) — The most probable action; the same protocol as act. Abschnitt 14.5
  • log_prob_np(obs, act) — log pi(a|s) for numpy batches of states and actions, as numpy. Abschnitt 14.5
  • probs(num_states, num_actions) — pi(a|s) for every pair, as a (num_states, num_actions) numpy array. Abschnitt 14.5

class PooledClassifier(nn.Module)

PooledClassifier(encoder, num_labels, pooling='mean', dropout=0.0)

A sentence or sentence-pair classifier on an encoder: the final ?sec-lm-bert

  • forward(input_ids, attention_mask)

class ProductQuantizer

ProductQuantizer(m, nbits=8)

Product quantization: a vector of d coordinates is cut into m ?sec-lm-retrieval

  • fit(X, n_iter=20, seed=0)
  • encode(X) — Codes (N, m), uint8: the nearest centroid of each sub-vector.
  • decode(codes) — The reconstructions x-hat (N, d) of codes.
  • adc_table(q) — (m, 2^nbits) squared distances of q’s sub-vectors to the
  • adc_search(q, codes, k) — (distances, ids) of the k codes nearest to the query q, or to

class ProgressBoard(d2l.HyperParameters)

ProgressBoard(xlabel=None, ylabel=None, xlim=None, ylim=None, xscale='linear', yscale='linear', figsize=(3.5, 2.5), display=True)

Curves that grow during training; show redraws them. Abschnitt 2.4

  • clear() — Forget all curves; the next show starts a new figure.
  • draw(x, y, label) — Append the point (x, y) to the curve called label.
  • show(final=True) — Redraw all curves; the book build renders only the final call. Abschnitt 39.9

class Qwen3Attention(d2l.CausalAttention)

Qwen3Attention(num_hiddens, num_heads, num_kv_heads, head_dim=None, qk_norm=False, rope_theta=10000.0, norm_eps=1e-06, bias=False, rope=True, causal=True)

Causal attention with separate projections, an explicit head width, ?sec-lm-d2l-checkpoint

  • qkv(X, offset=0, tables=None)
  • forward_step(X, cache, tables=None) — Attention output for X at positions t, …, t + T - 1, where cache

class Qwen3GPT(d2l.GPT)

Qwen3GPT(vocab_size, num_hiddens, num_heads, num_kv_heads, num_blks, head_dim=None, qk_norm=True, rope_theta=1000000.0, ffn_hidden=None, norm_eps=1e-06, tie_embeddings=True, max_len=40960, bias=False)

d2l.GPT with Qwen3’s head width, QK-norm, RoPE base, feed-forward ?sec-lm-d2l-checkpoint

  • CausalAttention(d, H, bias, rope, num_kv_heads) — The attention GPT builds in each block (a method, not a lambda,
  • forward(X, logits_to_keep=None, tables=None)
  • init_cache(batch_size, max_len) — Zeroed keys and values for every block, each (blocks, batch, kv ?sec-lm-d2l-checkpoint
  • forward_cached(X, ks, vs, t) — Logits after the last of the new tokens X, which sit at positions ?sec-lm-d2l-checkpoint
  • generate_cached(prefix, num_tokens, temperature=1.0, top_k=None) — Sample as generate does, but never recompute the prefix. ?sec-lm-d2l-checkpoint

class RAGPipeline

RAGPipeline(retriever, model, tokenizer, k=5, budget_tokens=3000, order='rank', rewrite=None, hyde=False, decompose=False, rerank_k=None, max_new_tokens=300, depth=50, dedup_cos=0.95, prompt='fixed', verify=False, abstain_below=None)

Retrieval-augmented generation over the book corpus. The question, ?sec-lm-rag

  • prepare(questions, budgets=None) — Phases 1 and 2. Per question (a string or an item dict): the
  • answer(questions, batch_size=8, contexts=None) — Phase 3 after prepare (or with the contexts given; a context of

class RNN(d2l.Module)

RNN(num_inputs, num_hiddens, sigma=0.01)

The RNN model implemented with high-level APIs. Abschnitt 8.4.6

  • forward(inputs, H=None)

class RNNLM(d2l.RNNLMScratch)

The RNN-based language model implemented with high-level APIs. Abschnitt 8.4.6

  • init_params()
  • embedding(X)
  • output_layer(hiddens)

class RNNLMScratch(d2l.Classifier)

RNNLMScratch(rnn, vocab_size, lr=0.01, dropout=0, emb_dropout=0)

The RNN-based language model implemented from scratch. Abschnitt 8.4.2

  • init_params()
  • validation_step(batch)
  • embedding(X)
  • output_layer(rnn_outputs)
  • forward(X, state=None)
  • predict(prefix, num_tokens, tok, device=None, temperature=0.0)

class RNNScratch(d2l.Module)

RNNScratch(num_inputs, num_hiddens, sigma=0.01)

The RNN model implemented from scratch. Abschnitt 8.4.2

  • forward(inputs, state=None)

class RecallModel(nn.Module)

RecallModel(layer, num_hiddens, vocab_size=16, num_inputs=32, num_outputs=8)

Embedding, a sequence layer, and a classifier at every position. Abschnitt 12.1.4

  • forward(X)

class Recurrent(nn.Module)

Recurrent(rnn)

A batch-first recurrent layer that returns only its outputs. Abschnitt 12.1.4

  • forward(X)

class ReplayBuffer

ReplayBuffer(capacity, obs_dim)

A ring of transitions in preallocated numpy; sample() returns a Batch. Abschnitt 15.4

  • add(obs, act, rew, next_obs, term)
  • sample(batch_size, rng) — batch_size transitions drawn uniformly, each a one-step

class ReplayBufferC(d2l.ReplayBuffer)

ReplayBufferC(capacity, obs_dim, act_dim)

d2l.ReplayBuffer with the action column widened to float vectors. Abschnitt 15.5

class ReplayMiss(KeyError)

A request that is not in the cache of a client in replay mode: a ?sec-lm-api

class ResNeXtBlock(nn.Module)

ResNeXtBlock(num_channels, groups, bot_mul, use_1x1conv=False, strides=1)

The ResNeXt block. Abschnitt 7.4

  • forward(X)

class Residual(nn.Module)

Residual(num_channels, use_1x1conv=False, strides=1)

The Residual block of ResNet models. Abschnitt 7.4

  • forward(X)

class S4D(nn.Module)

S4D(num_hiddens, num_states=16, dt_min=0.001, dt_max=0.1)

A diagonal state space layer: N states per channel, fixed dynamics. Abschnitt 12.4

  • discretize() — Zero-order hold with B = 1: decays a_bar and input weights b_bar.
  • forward(X)
  • step(x, h) — One step: x is (batch_size, d); the state h is (batch_size, d, N). Abschnitt 12.4

class SGD(d2l.HyperParameters)

SGD(params, lr)

Minibatch stochastic gradient descent. Abschnitt 2.4

  • step()
  • zero_grad()

class SelectiveSSM(nn.Module)

SelectiveSSM(num_channels, dt_rank, num_states=16, dt_min=0.001, dt_max=0.1, selective=True)

A diagonal SSM with N states for each of num_channels channels. Its Abschnitt 12.5

  • log_coefficients(U) — Log-decays and writes, each of shape (batch_size, T, H, N). Abschnitt 12.5
  • forward(U)

class SeqLM(nn.Module)

SeqLM(vocab_size, num_hiddens, mixers)

A language model of residual blocks: a sequence mixer, then an MLP. Abschnitt 12.1.4

  • forward(X)
  • first_mixer_input(X) — What the first mixer reads: the normalized token embeddings. Abschnitt 12.3

class Shift(nn.Module)

Shift(theta0)

The generator x’ = theta + z. Abschnitt 16.2

  • forward(z)

class SoftmaxRegression(d2l.Classifier)

SoftmaxRegression(num_outputs, lr)

The softmax regression model. Abschnitt 3.3.5

  • weight_init(module)
  • forward(X)

class SquashedGaussianPolicy(nn.Module)

SquashedGaussianPolicy(obs_dim, act_dim, hidden=64, scale=2.0, seed=None)

d2l.GaussianHead with SAC’s network (two ReLU layers and a Abschnitt 15.5

  • log_prob_u(u, mean, std) — log pi at a = scale tanh(u), from the pre-squash u the sampler
  • sample(obs) — A reparameterized action and its log-probability, differentiable.
  • act(obs, rng) — A sampled action, numpy in and out.
  • act_logp(obs, rng) — A sampled action and its log-probability, numpy in and out.
  • act_greedy(obs, rng=None) — The squashed mean scale * tanh(mean), numpy in and out.

class SwiGLU(d2l.FeedForward)

SwiGLU(num_hiddens, hidden, bias=False)

SwiGLU feed-forward network with an explicit hidden width. ?sec-lm-d2l-checkpoint

class SyntheticRegressionData(d2l.DataModule)

SyntheticRegressionData(w, b, noise=0.01, num_train=1000, num_val=1000, batch_size=32)

Synthetic data for linear regression. Abschnitt 2.4

  • get_dataloader(train)

class TabularMDP

TabularMDP(P, r, gamma)

A finite MDP as dense arrays: P[s, a, s’] and r[s, a]. Abschnitt 14.1

  • from_gym(env, gamma) — Read the transition table Gymnasium exposes as env.unwrapped.P.
  • backup(V) — Q(s, a) = r(s, a) + gamma * sum_{s’} P(s’|s, a) V(s’) for every Abschnitt 14.2
  • policy_value(pi) — V^pi = (I - gamma P_pi)^{-1} r_pi exactly, for pi[s, a] the Abschnitt 14.2

class TimeMLP(nn.Module)

TimeMLP(hidden=256, depth=3, dim=2, num_times=1, time_dim=64, time_freqs=(1.0, 64.0))

An MLP on a point x and the time features of one or more times; Abschnitt 17.1

  • forward(x, *ts)

class TimeMachine(d2l.DataModule)

TimeMachine(batch_size, num_steps, num_train=50000, num_val=5000, tokenization='bpe', vocab_size=1024)

The Time Machine dataset. Abschnitt 8.2

  • build(raw_text, vocab=None)
  • get_dataloader(train)

class Timer

Record multiple running times. Abschnitt 9.2.2

  • start() — Start the timer.
  • stop() — Stop the timer and record the time in a list.
  • avg() — Return the average time.
  • sum() — Return the sum of time.
  • cumsum() — Return the accumulated time.

class TinyCharLM(nn.Module)

TinyCharLM(vocab_size, num_hiddens=128, num_heads=4, num_blks=2, pos='rope', max_len=512, bias=False)

Attention-only language model. Abschnitt 10.4

  • stream(X, num_blks=None) — Residual stream after the first num_blks blocks (default: all),
  • forward(X)
  • attention_weights(X) — Per-block attention maps, each (batch, num_heads, T, T).
  • embed(X) — Token embeddings plus the absolute position code, if any. Abschnitt 10.4
  • alibi(T, device) — ALiBi bias -m_h (i - j) of every head, (num_heads, T, T). Abschnitt 10.4
  • attend(blk, H) — Output of attention block blk on the stream H, and its weights. Abschnitt 10.4

class TinyLM(nn.Module)

TinyLM(vocab_size, d_model=128, num_heads=2, num_blks=2, max_len=64)

A small decoder-only transformer language model. Abschnitt 9.5

  • attention(blk, X)
  • forward(X)

class TokenEmbedding

TokenEmbedding(embedding_name)

Token Embedding. ?sec-lm-word-embeddings

class TokenShards

TokenShards(root, split='train', fetch=False, max_tokens=None)

Read-only access to a shard set written by write_shards: documents ?sec-lm-tokenizers

  • shard(k)
  • offsets(k)
  • locate(i) — (shard, document within it, offset of its first token there).
  • locate_token(t) — (shard, position within it) of global token position t.
  • doc(i)
  • iter_docs(start=0)
  • read(start, n) — n tokens from global position start, across shard boundaries.
  • meta(k)
  • verify() — Recompute every file’s SHA-256 and check that offsets start at 0,

class TopKSAE(nn.Module)

TopKSAE(d_model, d_sae, k, center=False, seed=None)

Top-k sparse autoencoder with Qwen-Scope’s parameter names and ?sec-lm-interpretability

  • pre_acts(x)
  • topk_relu(pre, k) — ReLU of the k largest entries of each row, zero elsewhere; equal
  • encode(x)
  • decode(z)
  • forward(x)
  • loss(x, dead=None, k_aux=256) — Squared error normalized by the batch variance; the auxiliary
  • normalize_decoder_() — Project each decoder column onto the unit sphere (columns already
  • remove_parallel_grad_() — Remove from W_dec.grad each column’s component along the column,

class Tracker(d2l.Trainer)

Tracker(max_epochs, datasets)

A Trainer that records the accuracy on named datasets every epoch. Abschnitt 4.5

  • validate()

class Trainer(d2l.HyperParameters)

Trainer(max_epochs, num_gpus=0, gradient_clip_val=0)

Fit a Module to a DataModule, keeping a per-epoch history. Abschnitt 2.4

  • prepare_data(data)
  • prepare_optimizer(model) — configure_optimizers may also return a learning-rate scheduler. Abschnitt 2.4
  • fit(model, data)
  • record(split, metrics, x)
  • fit_epoch()
  • validate()
  • evaluate(model, data, train=False) — Metrics of model on the validation data of data (on its training Abschnitt 3.3
  • prepare_batch(batch)
  • prepare_model(model)
  • clip_gradients(grad_clip_val, model)

class TransformerBlock(nn.Module)

TransformerBlock(num_hiddens, num_heads, dropout=0, norm='rms', act='swiglu', pre_norm=True, bias=False, attn_factory=None, ffn_factory=None)

Configurable transformer block: attention + FFN on a residual Abschnitt 11.1

  • forward(X, mask=None, **attn_args)

class TunedLens(nn.Module)

TunedLens(d_model, num_layers)

One affine translator h + A_l h + b_l per block but the last (the ?sec-lm-interpretability

  • forward(hidden, layer)
  • logits(model, hidden, layer)
  • fit(model, batches, steps, lr=0.001, frac=0.25, seed=0, chunk=512) — Adam on KL(final || lens) summed over the layers, at a random

class UNet(nn.Module)

UNet(ch=64, num_classes=None, in_channels=1, out_channels=1, emb_dim=128, time_freqs=(1.0, 64.0))

A small U-Net on an image x (n, c, h, w), times t (n,) and labels y. Abschnitt 17.4

  • forward(x, t, y=None, cond=None)

class UNetBlock(nn.Module)

UNetBlock(c_in, c_out, emb_dim=None)

Two 3x3 convolutions with group norm, a residual, and an embedding. Abschnitt 17.4

  • forward(x, emb=None)

class UNetFlowMap(nn.Module)

UNetFlowMap(unet)

u(x, s, t): a velocity U-Net, plus a zero-initialized input for the Abschnitt 17.8

  • forward(x, s, t)

class UnigramTokenizer

UnigramTokenizer(vocab_size, seed_size=100000, em_iters=2, prune_frac=0.8, max_piece_len=12)

A unigram language model over pieces (Kudo 2018), trained by EM ?sec-lm-tokenizers

  • train(sentences)
  • encode(text)
  • encode_sample(text, alpha=0.2, seed=0) — A segmentation drawn with probability proportional to

class VOCSegDataset(torch.utils.data.Dataset)

VOCSegDataset(is_train, crop_size, voc_dir)

A customized dataset to load the VOC dataset. ?sec-semantic-segmentation

  • normalize_image(img)
  • filter(imgs)

class VerifierTask

Four prompts, nine candidate responses shared by all of them, an Abschnitt 14.1

  • verify(x, y) — The verifier: reward 1 iff response y is prompt x’s answer.
  • reward_table(reward) — reward(x, y) for every prompt x (rows) and response y (columns).
  • policy(theta) — pi(y | x): a softmax over each prompt’s row of preferences.
  • success(pi, reward=None) — E r(x, y), y ~ pi(. | x), averaged over the prompts; r = verify

class ViT(d2l.Classifier)

ViT(img_size, patch_size, num_hiddens, mlp_num_hiddens, num_heads, num_blks, num_steps, emb_dropout=0.0, blk_dropout=0.0, lr=0.001, use_bias=False, num_classes=10, num_channels=1)

Vision transformer. Abschnitt 11.5

  • forward(X)
  • configure_optimizers()

class ViTBlock(d2l.TransformerBlock)

ViTBlock(num_hiddens, mlp_num_hiddens, num_heads, dropout, use_bias=False)

Pre-norm block with LayerNorm and an exact-GELU MLP. Abschnitt 11.5

class Vocab

Vocab(tokens=(), min_freq=0, reserved_tokens=())

Vocabulary for text. Abschnitt 8.2

  • to_tokens(indices)
  • unk()

class WikiText103(d2l.DataModule)

WikiText103(batch_size, num_steps, num_train=None, num_val=None)

WikiText-103 as UTF-8 bytes, cut into windows of num_steps bytes. Abschnitt 9.5

  • windows(corpus, starts) — Inputs and next-byte targets of the windows at starts.
  • train_dataloader()
  • val_dataloader()

class reference_kernels

reference_kernels(model)

Run model on Transformers’ reference code inside a with block: ?sec-lm-hf-models

class seeded

seeded(seed)

In a with seeded(seed): block, PyTorch’s CPU generator starts from Abschnitt 14.5

class Accumulator

Accumulator(n)

For accumulating sums over n variables. Abschnitt 39.9

  • add(*args)
  • reset()

class Animator

Animator(xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1, figsize=(3.5, 2.5))

For plotting data in animation. Abschnitt 39.9

  • add(x, y)

class ArrayData(d2l.DataModule)

ArrayData(X, y, batch_size=64)

Minibatches of the arrays X and y; training batches are shuffled. Abschnitt 4.5

  • get_dataloader(train)

class Averager

Example-weighted means of batch metrics, summed on the device. Abschnitt 2.4

  • add(metrics, n)
  • mean() — One host synchronization per metric; the loss comes first.

class BPETokenizer

BPETokenizer(vocab_size=1024, pattern=None, specials=('<pad>', '<bos>', '<eos>'))

Byte-level BPE tokenizer trained by iterated most-frequent-pair Abschnitt 8.2

  • pad()
  • bos()
  • eos()
  • train(text) — Learn vocab_size - 256 merges, most frequent pair first. Abschnitt 8.2
  • encode(text, allow_special=False)
  • decode(ids)
  • from_tiktoken(name) — Load a published bytes->rank table (e.g. ‘gpt2’) into our encoder. Abschnitt 8.2

class BananasDataset

BananasDataset(is_train)

A customized dataset to load the banana detection dataset. ?sec-object-detection-dataset

class Benchmark

Benchmark(f, warmup=3, repeats=10, desc='time')

Time a callable: warmup, then device-synchronized average seconds. Abschnitt 5.7

class Classifier(d2l.Module)

The base class of classification models. Abschnitt 3.3

  • validation_step(batch)
  • accuracy(Y_hat, Y, averaged=True) — Compute the fraction of correct predictions. Abschnitt 3.3
  • loss(Y_hat, Y, averaged=True)
  • layer_summary(X_shape)

class DataModule(d2l.HyperParameters)

DataModule(root='../data', num_workers=4)

The base class of data. Abschnitt 2.4

  • get_dataloader(train)
  • train_dataloader()
  • val_dataloader()
  • get_tensorloader(tensors, train, indices=slice(0, None))

class FashionMNIST(d2l.DataModule)

FashionMNIST(batch_size=64, resize=(28, 28))

The Fashion-MNIST dataset. Abschnitt 3.2

  • text_labels(indices) — Return text labels. Abschnitt 3.2
  • get_dataloader(train)
  • visualize(batch, nrows=1, ncols=8, labels=None) — Show the images of a batch in grayscale, titled by their labels. Abschnitt 3.2

class HyperParameters

The base class of hyperparameters. Abschnitt 39.9

  • save_hyperparameters(ignore=None) — Save function arguments into instance attributes. Abschnitt 39.9

class LeNet(d2l.Classifier)

LeNet(lr=0.1, num_classes=10)

The layout of LeNet-5, with sigmoid activations and average pooling. Abschnitt 6.6

class LinearRegression(d2l.Module)

LinearRegression(lr)

Linear regression built from framework components. Abschnitt 2.5

  • loss(y_hat, y)
  • configure_optimizers()
  • get_w_b()

class LinearRegressionScratch(d2l.Module)

LinearRegressionScratch(num_inputs, lr, sigma=0.01)

The linear regression model implemented from scratch. Abschnitt 2.4

  • forward(X)
  • loss(y_hat, y)
  • configure_optimizers()

class MaskedSoftmaxCELoss(tf.keras.losses.Loss)

MaskedSoftmaxCELoss(valid_len)

The softmax cross-entropy loss with masks. Abschnitt 39.9

  • call(label, pred)

class Module(tf.keras.Model, d2l.HyperParameters)

The base class of models. Abschnitt 2.4

  • loss(y_hat, y)
  • forward(X)
  • call(X, *args, training=None, **kwargs)
  • training_step(batch) — The mean loss on one minibatch, or a dict of batch-mean metrics
  • validation_step(batch) — The mean loss on one minibatch of validation data, or a dict of
  • configure_optimizers()

class ProgressBoard(d2l.HyperParameters)

ProgressBoard(xlabel=None, ylabel=None, xlim=None, ylim=None, xscale='linear', yscale='linear', figsize=(3.5, 2.5), display=True)

Curves that grow during training; show redraws them. Abschnitt 2.4

  • clear() — Forget all curves; the next show starts a new figure.
  • draw(x, y, label) — Append the point (x, y) to the curve called label.
  • show(final=True) — Redraw all curves; the book build renders only the final call. Abschnitt 39.9

class RNN(d2l.Module)

RNN(num_inputs, num_hiddens, sigma=0.01)

The RNN model implemented with high-level APIs. Abschnitt 8.4.6

  • call(inputs, H=None, training=None)
  • forward(inputs, H=None)

class RNNLM(d2l.RNNLMScratch)

The RNN-based language model implemented with high-level APIs. Abschnitt 8.4.6

  • init_params()
  • embedding(X)
  • output_layer(hiddens)

class RNNLMScratch(d2l.Classifier)

RNNLMScratch(rnn, vocab_size, lr=0.01, dropout=0, emb_dropout=0)

The RNN-based language model implemented from scratch. Abschnitt 8.4.2

  • init_params()
  • validation_step(batch)
  • embedding(X)
  • output_layer(rnn_outputs)
  • forward(X, state=None)
  • predict(prefix, num_tokens, tok, device=None, temperature=0.0)

class RNNScratch(d2l.Module)

RNNScratch(num_inputs, num_hiddens, sigma=0.01)

The RNN model implemented from scratch. Abschnitt 8.4.2

  • forward(inputs, state=None)

class ResNeXtBlock(tf.keras.Model)

ResNeXtBlock(num_channels, groups, bot_mul, use_1x1conv=False, strides=1)

The ResNeXt block. Abschnitt 7.4

  • call(X)

class Residual(tf.keras.Model)

Residual(num_channels, use_1x1conv=False, strides=1)

The Residual block of ResNet models. Abschnitt 7.4

  • call(X)

class SGD(d2l.HyperParameters)

SGD(lr)

Minibatch stochastic gradient descent. Abschnitt 2.4

  • apply_gradients(grads_and_vars)

class SoftmaxRegression(d2l.Classifier)

SoftmaxRegression(num_outputs, lr)

The softmax regression model. Abschnitt 3.3.5

  • forward(X)

class SyntheticRegressionData(d2l.DataModule)

SyntheticRegressionData(w, b, noise=0.01, num_train=1000, num_val=1000, batch_size=32)

Synthetic data for linear regression. Abschnitt 2.4

  • get_dataloader(train)

class TimeMachine(d2l.DataModule)

TimeMachine(batch_size, num_steps, num_train=50000, num_val=5000, tokenization='bpe', vocab_size=1024)

The Time Machine dataset. Abschnitt 8.2

  • build(raw_text, vocab=None)
  • get_dataloader(train)

class Timer

Record multiple running times. Abschnitt 9.2.2

  • start() — Start the timer.
  • stop() — Stop the timer and record the time in a list.
  • avg() — Return the average time.
  • sum() — Return the sum of time.
  • cumsum() — Return the accumulated time.

class Tracker(d2l.Trainer)

Tracker(max_epochs, datasets)

A Trainer that records the accuracy on named datasets every epoch. Abschnitt 4.5

  • validate()

class TrainCallback(tf.keras.callbacks.Callback)

TrainCallback(net, train_iter, test_iter, num_epochs, device_name)

A callback to visualize the training progress. Abschnitt 39.9

  • on_epoch_begin(epoch, logs=None)
  • on_epoch_end(epoch, logs)

class Trainer(d2l.HyperParameters)

Trainer(max_epochs, num_gpus=0, gradient_clip_val=0)

Fit a Module to a DataModule, keeping a per-epoch history. Abschnitt 2.4

  • prepare_data(data)
  • prepare_optimizer(model)
  • fit(model, data)
  • record(split, metrics, x)
  • prepare_model(model)
  • train_step(batch)
  • val_step(batch)
  • fit_epoch()
  • validate()
  • evaluate(model, data, train=False) — Metrics of model on the validation data of data (on its training Abschnitt 3.3
  • prepare_batch(batch)
  • clip_gradients(grad_clip_val, grads)

class VOCSegDataset

VOCSegDataset(is_train, crop_size, voc_dir)

A customized dataset to load the VOC dataset. ?sec-semantic-segmentation

  • normalize_image(img)
  • filter(imgs)

class Vocab

Vocab(tokens=(), min_freq=0, reserved_tokens=())

Vocabulary for text. Abschnitt 8.2

  • to_tokens(indices)
  • unk()

class Accumulator

Accumulator(n)

For accumulating sums over n variables. Abschnitt 39.9

  • add(*args)
  • reset()

class ActorCritic(d2l.Policy)

ActorCritic(policy, value, lr=0.01)

A policy and a value function, each with its own optimizer. Abschnitt 14.9

  • V(obs, value=None) — V(s) for a batch of states; value plays the part of policy
  • value_np(obs) — V(s) for a numpy batch of states, as numpy, through a forward
  • tabular(num_states, num_actions, lr=0.1, seed=None) — Preference and value tables: two zero-initialized embeddings.
  • mlp(obs_dim, num_actions, hidden=64, lr=0.01, seed=None) — The same container with the tables replaced by one-hidden-layer nets. Abschnitt 14.9

class Animator

Animator(xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1, figsize=(3.5, 2.5))

For plotting data in animation. Abschnitt 39.9

  • add(x, y)

class ArrayData(d2l.DataModule)

ArrayData(X, y, batch_size=64)

Minibatches of the arrays X and y; training batches are shuffled. Abschnitt 4.5

  • get_dataloader(train)

class ArrayDataLoader(d2l.ArrayLoader)

ArrayDataLoader(*args, batch_size=32, shuffle=False, drop_last=False)

d2l.ArrayLoader that yields JAX arrays and also accepts a dataset. Abschnitt 39.9

class ArrayLoader

ArrayLoader(arrays, batch_size, shuffle=False, drop_last=False, key=None)

Minibatches of in-memory arrays, reshuffled each pass if shuffle. Abschnitt 2.4

class AttentionMixer(d2l.CausalAttention)

AttentionMixer(num_hiddens, num_heads, conv_width=None, rope=True, rngs)

Causal multi-head attention, with rotary positions unless rope is Abschnitt 12.1.4

  • qkv(X, offset=0, tables=None)

class Autoencoder(nnx.Module)

Autoencoder(latent_channels=4, ch=64, num_blocks=2, rngs)

Residual convolutional autoencoder from 28x28x1 images to a 7x7 Abschnitt 17.7

  • encode(x)

class Averager

Example-weighted means of batch metrics, summed on the device. Abschnitt 2.4

  • add(metrics, n)
  • mean() — One host synchronization per metric; the loss comes first.

class BPETokenizer

BPETokenizer(vocab_size=1024, pattern=None, specials=('<pad>', '<bos>', '<eos>'))

Byte-level BPE tokenizer trained by iterated most-frequent-pair Abschnitt 8.2

  • pad()
  • bos()
  • eos()
  • train(text) — Learn vocab_size - 256 merges, most frequent pair first. Abschnitt 8.2
  • encode(text, allow_special=False)
  • decode(ids)
  • from_tiktoken(name) — Load a published bytes->rank table (e.g. ‘gpt2’) into our encoder. Abschnitt 8.2
  • to_tokens(ids)

class BananasDataset

BananasDataset(is_train)

A customized dataset to load the banana detection dataset. ?sec-object-detection-dataset

class Batch

Batch(obs, act, rew, next_obs, term, ep_ends)

A flat batch of transitions, plus the episode boundaries. Abschnitt 14.7

  • episodes() — Yield one slice per episode.
  • episode_returns(gamma=1.0) — R(tau), the discounted return, one number per episode.
  • per_step(values) — Repeat one value per episode over that episode’s steps.
  • backward_scan(x, factor) — y_t = x_t + factor * y_{t+1}, restarted at every episode boundary. Abschnitt 14.8
  • reward_to_go(gamma) — G_t: the discounted return of the rest of its episode, by one scan. Abschnitt 14.8
  • truncation_bootstrap(gamma, V) — gamma^(T-t) (1 - term_T) V(s_T) for every step t of each episode: Abschnitt 14.9
  • td_target(bootstrap, gamma) — r_t + gamma (1 - terminated) V(s’), by a numpy bootstrap. Abschnitt 15.1
  • gae(value_fn, gamma, lam) — GAE(gamma, lam): the reward-to-go scan, run on the TD errors. Abschnitt 15.1
  • lambda_return(value_fn, gamma, lam) — The critic’s target for GAE: the advantage plus the value it is Abschnitt 15.1

class Benchmark

Benchmark(f, warmup=3, repeats=10, desc='time')

Time a callable: warmup, then device-synchronized average seconds. Abschnitt 5.7

class CausalAttention(nnx.Module)

CausalAttention(num_hiddens, num_heads, bias=False, rope=False, num_kv_heads=None, rngs)

Causal self-attention, optionally rotary; num_kv_heads < num_heads Abschnitt 11.2

  • qkv(X, offset=0, tables=None) — Queries, keys, and values of X, each (batch, heads, length, head
  • attend(q, k, v) — Causal attention of (batch, length, heads, head width) queries,

class Classifier(d2l.Module)

The base class of classification models. Abschnitt 3.3

  • validation_step(batch)
  • accuracy(Y_hat, Y, averaged=True) — Compute the fraction of correct predictions. Abschnitt 3.3
  • loss(Y_hat, Y, averaged=True)
  • layer_summary(X_shape)

class Conv(nnx.Conv)

Conv(in_features, out_features, kernel_size, rngs, **kwargs)

nnx.Conv (kernel_size a tuple), all weights from U(+-1/sqrt(fan_in)). Abschnitt 17.4

class DataModule(d2l.HyperParameters)

DataModule(root='../data', num_workers=4)

The base class of data. Abschnitt 2.4

  • get_dataloader(train)
  • train_dataloader()
  • val_dataloader()
  • get_tensorloader(tensors, train, indices=slice(0, None))

class DiT(nnx.Module)

DiT(img_size=28, patch_size=4, num_channels=1, width=256, depth=6, num_heads=4, num_classes=None, rngs)

Diffusion transformer (NHWC) conditioned on a time t in [0, 1] and, Abschnitt 17.7

class DiTBlock(d2l.ViTBlock)

DiTBlock(num_hiddens, mlp_num_hiddens, num_heads, rngs)

ViTBlock with adaLN-Zero: the condition c sets a shift, a scale and a Abschnitt 17.7

class Discriminator(nnx.Module)

Discriminator(resolution, base_ch, rngs)

Critic that mirrors the generator: conv + leaky ReLU + bilinear Abschnitt 16.5

  • phi(x)

class DotProductAttention(nnx.Module)

DotProductAttention(dropout=0.0, rngs=None)

Scaled dot-product attention over the last two axes. Abschnitt 10.2

  • attention_weights() — Weights of the last eager call: (…, queries, keys).

class EMA

EMA(model, half_life)

Exponential moving average of a model’s parameters, given as a Abschnitt 16.5

  • update(model)
  • average(avg, model, decay) — Move the parameters of avg toward those of model, in place.

class Embed(nnx.Embed)

nnx.Embed whose gradient is a matrix product for small vocabularies. Abschnitt 39.9

class FashionCNN(nnx.Module)

FashionCNN(rngs)

A compact CNN for Fashion-MNIST: two conv-pool stages, two linear. Abschnitt 9.5

class FashionMNIST(d2l.DataModule)

FashionMNIST(batch_size=64, resize=(28, 28))

The Fashion-MNIST dataset. Abschnitt 3.2

  • text_labels(indices) — Return text labels. Abschnitt 3.2
  • get_dataloader(train)
  • visualize(batch, nrows=1, ncols=8, labels=None) — Show the images of a batch in grayscale, titled by their labels. Abschnitt 3.2

class FeatureCNN(nnx.Module)

FeatureCNN(feature_dim=128, resolution=32, rngs=None)

Three conv blocks, global average pooling, and a linear head. Inputs Abschnitt 39.9

  • features(x)

class FeedForward(nnx.Module)

FeedForward(num_hiddens, act='swiglu', bias=False, rngs)

Position-wise FFN: GELU MLP or SwiGLU at matched parameter count. Abschnitt 11.1

class GPT(nnx.Module)

GPT(vocab_size, num_hiddens=256, num_heads=8, num_blks=6, max_len=1024, pos='rope', norm='rms', act='swiglu', pre_norm=True, bias=False, dropout=0, num_kv_heads=None, ffn_factory=None, rngs)

Decoder-only transformer language model built from configurable Abschnitt 11.2

  • init_weights(rngs) — GPT-2’s initialization of the linear layers: N(0, 0.02^2) weights and Abschnitt 11.2
  • generate(prefix, num_tokens, temperature=1.0, top_k=None) — Sample a continuation of the token-id list prefix. Abschnitt 11.2

class GatedDeltaNet(d2l.GatedLinearAttention)

GatedDeltaNet(num_hiddens, num_heads, chunk_size=32, conv_width=4, timescales=(4, 256), rngs)

Gated linear attention whose memory is written by the delta rule. Abschnitt 12.7

  • memory(X, Q, K, V, log_a)

class GatedLinearAttention(nnx.Module)

GatedLinearAttention(num_hiddens, num_heads, chunk_size=16, conv_width=4, timescales=(4, 256), rngs)

Multi-head linear attention with one input-dependent decay per head. Abschnitt 12.6

  • init_decays(tau_min, tau_max) — Start the decays at exp(-1/tau), tau log-uniform in range.
  • decays(X) — Log decays, (batch_size * num_heads, T). Abschnitt 12.6
  • memory(X, Q, K, V, log_a) — Outputs of the decayed matrix memory of every head. X is unused here; Abschnitt 12.6

class GaussianHead(nnx.Module)

GaussianHead(obs_dim, act_dim, hidden, state_std=False, trunk=None, zero_mean=False, rngs)

A Gaussian over actions: a trunk of hidden features, a linear mean, Abschnitt 14.9

class GaussianMixture

GaussianMixture(means, weights, std)

A mixture of isotropic Gaussians, exact at every noise level. Abschnitt 17.1

  • three_modes() — The chapter’s running example, with mode weights 0.5/0.3/0.2.
  • sample(key, n) — n draws from the mixture.
  • log_prob(x, alpha=1.0, sigma=0.0) — log p(x) for x = alpha x0 + sigma eps.
  • score(x, alpha=1.0, sigma=0.0) — The gradient of log p(x) for x = alpha x0 + sigma eps.
  • posterior_mean(x, alpha, sigma) — E[x0 | x]; finite at alpha = 0 and at sigma = 0.
  • nll(x) — Mean negative log-likelihood of clean points, in nats. Abschnitt 17.1
  • summary(x) — Mode weights by nearest mean, stray fraction, spread of the rest. Abschnitt 17.1
  • velocity(x, t) — E[eps - x0 | x_t] on the linear path x_t = (1 - t) x0 + t eps. Abschnitt 17.2

class GaussianPath

GaussianPath(alpha, sigma)

x_t = alpha(t) x0 + sigma(t) eps, data at t = 0 and noise at t = 1. Abschnitt 17.2

  • vp(beta_min=0.1, beta_max=20.0) — Variance preserving, Ho et al.’s linear beta in continuous time.
  • linear() — The straight line of flow matching and rectified flow.
  • cosine(s=0.008) — Variance preserving, Nichol and Dhariwal’s cosine schedule.
  • log_snr(t) — lambda_t = log(alpha_t^2 / sigma_t^2), falling from +inf at 0.
  • sample(x0, t, eps) — x_t for per-example times t of shape (n,).
  • grid(steps, t_start=1.0, t_end=0.0) — Arrays of alpha and sigma at steps + 1 even times, t_start to t_end. Abschnitt 17.2
  • rates(t) — The time derivatives (alpha’(t), sigma’(t)), by forward-mode AD. Abschnitt 17.2
  • target(kind, x0, eps, t) — The regression target of a kind: eps, x0, v, score or velocity. Abschnitt 17.2
  • x0_eps(kind, out, x, t) — The (x0, eps) that a prediction out of a kind implies at (x, t). Abschnitt 17.2
  • sigma_bars(steps) — sigma_bar = sigma / alpha on the grid of steps; inf where alpha = 0. Abschnitt 17.3
  • time_at(log_snr) — The time with a given log-SNR, by bisection (lambda_t falls in t). Abschnitt 17.3

class GaussianPolicy(ActorCritic)

GaussianPolicy(obs_dim, act_dim, hidden=64, lr=0.01, seed=None, **head_args)

The same interface over a Normal instead of a softmax; nothing that Abschnitt 14.9

  • log_prob(obs, act, policy=None) — log pi(a|s): the Normal density, summed over action dimensions.
  • act(obs, rng) — Sample mu(s) + sigma(s) z, z ~ N(0, I) from the numpy rng.
  • act_greedy(obs, rng=None) — The mean action mu(s).

class Generator(nnx.Module)

Generator(latent_dim, resolution, base_ch, extra_ch=0, const_ch=128, rngs)

Learned 4x4 constant + projected latent (+ extra 4x4 input maps), Abschnitt 16.5

class HyperParameters

The base class of hyperparameters. Abschnitt 39.9

  • save_hyperparameters(ignore=None) — Save function arguments into instance attributes. Abschnitt 39.9

class LMOptimizer(nnx.Optimizer)

LMOptimizer(model, lr, num_steps, warmup, weight_decay=0.1, max_norm=1.0)

AdamW with weight decay on the weight matrices only, a linear warmup Abschnitt 11.2

class LeNet(d2l.Classifier)

LeNet(lr=0.1, num_classes=10, kernel_init=None, rngs=None)

The layout of LeNet-5, with sigmoid activations and average pooling. Abschnitt 6.6

class Linear(nnx.Linear)

Linear(in_features, out_features, use_bias=True, rngs, **kwargs)

nnx.Linear with weights and biases drawn from U(-a, a), where Abschnitt 10.3

class LinearRegression(d2l.Module)

LinearRegression(num_inputs, lr, rngs=None)

Linear regression built from framework components. Abschnitt 2.5

  • loss(y_hat, y)
  • configure_optimizers()
  • get_w_b()

class LinearRegressionScratch(d2l.Module)

LinearRegressionScratch(num_inputs, lr, sigma=0.01, rngs=None)

The linear regression model implemented from scratch. Abschnitt 2.4

  • forward(X)
  • loss(y_hat, y)
  • configure_optimizers()

class Mamba(nnx.Module)

Mamba(num_hiddens, num_states=16, expand=2, conv_width=4, rngs, **ssm_args)

The Mamba layer: a gated selective SSM between two projections. Abschnitt 12.5

  • ssm_input(X) — The input of the SSM and the gate branch.

class MinGRU(nnx.Module)

MinGRU(num_inputs, num_hiddens, rngs)

The minimal GRU: its gate and candidate read only the input. Abschnitt 12.3

  • coefficients(X) — Decays a_t and writes b_t of the linear recurrence.

class MixtureGenerator(nnx.Module)

MixtureGenerator(mu, A)

x = mu_k + z A_k for a uniformly drawn component k. Abschnitt 16.2

  • params_np()

class Module(nnx.Module, d2l.HyperParameters)

The base class of models. Abschnitt 2.4

  • loss(y_hat, y)
  • forward(X, *args, **kwargs)
  • training_step(batch) — The mean loss on one minibatch, or a dict of batch-mean metrics
  • validation_step(batch) — The mean loss on one minibatch of validation data, or a dict of
  • configure_optimizers()

class MultiHeadAttention(nnx.Module)

MultiHeadAttention(num_hiddens, num_heads, dropout=0.0, bias=False, num_kv_heads=None, rngs)

Multi-head attention with heads as an explicit axis; num_kv_heads < Abschnitt 10.3

  • attention_weights() — Weights of the last call: (batch, num_heads, queries, keys).
  • split_heads(X, num_heads) — (batch, length, num_heads * width) -> (batch, num_heads, length, Abschnitt 10.3
  • merge_heads(X) — Reverse split_heads: (batch, num_heads, length, width) -> (batch, Abschnitt 10.3

class PatchEmbedding(nnx.Module)

PatchEmbedding(img_size=96, patch_size=16, num_hiddens=512, num_channels=3, rngs)

Image-to-sequence stem of the vision transformer. Abschnitt 11.5

class Policy(nnx.Module)

Policy(policy, lr=0.01)

A policy network and its optimizer; pi(.|s) is the softmax of the Abschnitt 14.5

  • log_prob(obs, act, policy=None) — log pi(a|s). Gradients flow w.r.t. the module you differentiate;
  • tabular(num_states, num_actions, lr=0.1, seed=None) — One preference theta_{s,a} per state-action pair: an embedding.
  • act(obs, rng) — Sample an action; numpy in, int out, the acting protocol of evaluate. Abschnitt 14.5
  • act_greedy(obs, rng=None) — The most probable action; the same protocol as act. Abschnitt 14.5
  • log_prob_np(obs, act) — log pi(a|s) for numpy batches of states and actions, as numpy. The Abschnitt 14.5
  • probs(num_states, num_actions) — pi(a|s) for every pair, as a (num_states, num_actions) numpy array. Abschnitt 14.5

class ProgressBoard(d2l.HyperParameters)

ProgressBoard(xlabel=None, ylabel=None, xlim=None, ylim=None, xscale='linear', yscale='linear', figsize=(3.5, 2.5), display=True)

Curves that grow during training; show redraws them. Abschnitt 2.4

  • clear() — Forget all curves; the next show starts a new figure.
  • draw(x, y, label) — Append the point (x, y) to the curve called label.
  • show(final=True) — Redraw all curves; the book build renders only the final call. Abschnitt 39.9

class RNN(nnx.Module)

RNN(num_inputs, num_hiddens, sigma=0.01, rngs=None)

The RNN model implemented with high-level APIs. Abschnitt 8.4.6

class RNNLM(d2l.RNNLMScratch)

RNNLM(rnn, vocab_size, lr=0.01, dropout=0, emb_dropout=0, rngs=None)

The RNN-based language model implemented with high-level APIs. Abschnitt 8.4.6

  • embedding(X)
  • output_layer(hiddens)

class RNNLMScratch(d2l.Classifier)

RNNLMScratch(rnn, vocab_size, lr=0.01, dropout=0, emb_dropout=0, rngs=None)

The RNN-based language model implemented from scratch. Abschnitt 8.4.2

  • validation_step(batch)
  • embedding(X)
  • output_layer(rnn_outputs)
  • forward(X, state=None)
  • predict(prefix, num_tokens, tok, device=None, temperature=0.0)

class RNNScratch(nnx.Module)

RNNScratch(num_inputs, num_hiddens, sigma=0.01, rngs=None)

The RNN model implemented from scratch. Abschnitt 8.4.2

class RecallModel(nnx.Module)

RecallModel(layer, num_hiddens, vocab_size=16, num_inputs=32, num_outputs=8, rngs)

Embedding, a sequence layer, and a classifier at every position. Abschnitt 12.1.4

class ReplayBuffer

ReplayBuffer(capacity, obs_dim)

A ring of transitions in preallocated numpy; sample() returns a Batch. Abschnitt 15.4

  • add(obs, act, rew, next_obs, term)
  • sample(batch_size, rng) — batch_size transitions drawn uniformly, each a one-step

class ReplayBufferC(d2l.ReplayBuffer)

ReplayBufferC(capacity, obs_dim, act_dim)

d2l.ReplayBuffer with the action column widened to float vectors. Abschnitt 15.5

class ResNeXtBlock(nnx.Module)

ResNeXtBlock(num_channels, groups, bot_mul, use_1x1conv=False, strides=(1, 1), in_channels=None, rngs=None)

The ResNeXt block. Abschnitt 7.4

class Residual(nnx.Module)

Residual(num_channels, use_1x1conv=False, strides=(1, 1), in_channels=None, rngs=None)

The Residual block of ResNet models. Abschnitt 7.4

class S4D(nnx.Module)

S4D(num_hiddens, num_states=16, dt_min=0.001, dt_max=0.1, rngs)

A diagonal state space layer: N states per channel, fixed dynamics. Abschnitt 12.4

  • discretize() — Zero-order hold with B = 1: decays a_bar and input weights b_bar.
  • step(x, h) — One step: x is (batch_size, d); the state h is (batch_size, d, N). Abschnitt 12.4

class SGD(d2l.HyperParameters)

SGD(lr)

Minibatch stochastic gradient descent. Abschnitt 2.4

  • init(params)
  • update(updates, state, params=None)

class SelectiveSSM(nnx.Module)

SelectiveSSM(num_channels, dt_rank, num_states=16, dt_min=0.001, dt_max=0.1, selective=True, rngs)

A diagonal SSM with N states for each of num_channels channels. Its Abschnitt 12.5

  • log_coefficients(U) — Log-decays and writes, each of shape (batch_size, T, H, N). Abschnitt 12.5

class SeqLM(nnx.Module)

SeqLM(vocab_size, num_hiddens, mixers, rngs)

A language model of residual blocks: a sequence mixer, then an MLP. Abschnitt 12.1.4

  • first_mixer_input(X) — What the first mixer reads: the normalized token embeddings. Abschnitt 12.3

class Shift(nnx.Module)

Shift(theta0)

The generator x’ = theta + z. Abschnitt 16.2

class SoftmaxRegression(d2l.Classifier)

SoftmaxRegression(num_outputs, lr, num_inputs=784, rngs=None)

The softmax regression model. Abschnitt 3.3.5

  • forward(X)

class SquashedGaussianPolicy(nnx.Module)

SquashedGaussianPolicy(obs_dim, act_dim, hidden=64, scale=2.0, seed=None)

d2l.GaussianHead with SAC’s network (two ReLU layers and a Abschnitt 15.5

  • log_prob_u(u, mean, std) — log pi at a = scale tanh(u), from the pre-squash u the sampler
  • sample(obs, key) — A reparameterized action and its log-probability, differentiable.
  • act(obs, rng) — A sampled action, numpy in and out.
  • act_logp(obs, rng) — A sampled action and its log-probability, numpy in and out.
  • act_greedy(obs, rng=None) — The squashed mean scale * tanh(mean), numpy in and out.

class SyntheticRegressionData(d2l.DataModule)

SyntheticRegressionData(w, b, noise=0.01, num_train=1000, num_val=1000, batch_size=32, key=None)

Synthetic data for linear regression. Abschnitt 2.4

  • get_dataloader(train)

class TabularMDP

TabularMDP(P, r, gamma)

A finite MDP as dense arrays: P[s, a, s’] and r[s, a]. Abschnitt 14.1

  • from_gym(env, gamma) — Read the transition table Gymnasium exposes as env.unwrapped.P.
  • backup(V) — Q(s, a) = r(s, a) + gamma * sum_{s’} P(s’|s, a) V(s’) for every Abschnitt 14.2
  • policy_value(pi) — V^pi = (I - gamma P_pi)^{-1} r_pi exactly, for pi[s, a] the Abschnitt 14.2

class TensorFlowDataLoader

TensorFlowDataLoader(dataset)

Expose a tf.data.Dataset as re-iterable NumPy batches. Abschnitt 3.2

class TimeMLP(nnx.Module)

TimeMLP(hidden=256, depth=3, dim=2, num_times=1, time_dim=64, time_freqs=(1.0, 64.0), rngs)

An MLP on a point x and the time features of one or more times; Abschnitt 17.1

class TimeMachine(d2l.DataModule)

TimeMachine(batch_size, num_steps, num_train=50000, num_val=5000, tokenization='bpe', vocab_size=1024)

The Time Machine dataset. Abschnitt 8.2

  • build(raw_text, vocab=None)
  • get_dataloader(train)

class Timer

Record multiple running times. Abschnitt 9.2.2

  • start() — Start the timer.
  • stop() — Stop the timer and record the time in a list.
  • avg() — Return the average time.
  • sum() — Return the sum of time.
  • cumsum() — Return the accumulated time.

class TinyCharLM(nnx.Module)

TinyCharLM(vocab_size, num_hiddens=128, num_heads=4, num_blks=2, pos='rope', max_len=512, bias=False, rngs)

Attention-only language model. Abschnitt 10.4

  • stream(X, num_blks=None) — Residual stream after the first num_blks blocks (default: all),
  • attention_weights(X) — Per-block attention maps, each (batch, num_heads, T, T).
  • embed(X) — Token embeddings plus the absolute position code, if any. Abschnitt 10.4
  • alibi(T) — ALiBi bias -m_h (i - j) of every head, (num_heads, T, T). Abschnitt 10.4
  • attend(blk, H) — Output of attention block blk on the stream H, and its weights. Abschnitt 10.4

class TinyLM(nnx.Module)

TinyLM(vocab_size, d_model=128, num_heads=2, num_blks=2, max_len=64, rngs)

A small decoder-only transformer language model. Abschnitt 9.5

  • attention(blk, X)

class Tracker(d2l.Trainer)

Tracker(max_epochs, datasets)

A Trainer that records the accuracy on named datasets every epoch. Abschnitt 4.5

  • validate()

class Trainer(d2l.HyperParameters)

Trainer(max_epochs, num_gpus=0, gradient_clip_val=0)

Fit a Module to a DataModule, keeping a per-epoch history. Abschnitt 2.4

  • prepare_data(data)
  • prepare_model(model)
  • fit(model, data)
  • record(split, metrics, x)
  • fit_epoch()
  • validate()
  • evaluate(model, data, train=False) — Metrics of model on the validation data of data (on its training Abschnitt 3.3
  • prepare_batch(batch)
  • prepare_optimizer(model)

class TransformerBlock(nnx.Module)

TransformerBlock(num_hiddens, num_heads, dropout=0, norm='rms', act='swiglu', pre_norm=True, bias=False, attn_factory=None, ffn_factory=None, rngs)

Configurable transformer block: attention + FFN on a residual Abschnitt 11.1

class UNet(nnx.Module)

UNet(ch=64, num_classes=None, in_channels=1, out_channels=1, emb_dim=128, time_freqs=(1.0, 64.0), rngs)

A small U-Net on an image x (n, h, w, c), times t (n,) and labels y. Abschnitt 17.4

class UNetBlock(nnx.Module)

UNetBlock(c_in, c_out, emb_dim=None, rngs)

Two 3x3 convolutions with group norm, a residual, and an embedding. Abschnitt 17.4

class UNetFlowMap(nnx.Module)

UNetFlowMap(unet, rngs)

u(x, s, t): a velocity U-Net, plus a zero-initialized input for the Abschnitt 17.8

class VOCSegDataset

VOCSegDataset(is_train, crop_size, voc_dir)

A customized dataset to load the VOC dataset. ?sec-semantic-segmentation

  • normalize_image(img)
  • filter(imgs)

class VerifierTask

Four prompts, nine candidate responses shared by all of them, an Abschnitt 14.1

  • verify(x, y) — The verifier: reward 1 iff response y is prompt x’s answer.
  • reward_table(reward) — reward(x, y) for every prompt x (rows) and response y (columns).
  • policy(theta) — pi(y | x): a softmax over each prompt’s row of preferences.
  • success(pi, reward=None) — E r(x, y), y ~ pi(. | x), averaged over the prompts; r = verify

class ViT(d2l.Classifier)

ViT(img_size, patch_size, num_hiddens, mlp_num_hiddens, num_heads, num_blks, num_steps, emb_dropout=0.0, blk_dropout=0.0, lr=0.001, use_bias=False, num_classes=10, num_channels=1, rngs)

Vision transformer. Abschnitt 11.5

  • forward(X)
  • configure_optimizers()

class ViTBlock(d2l.TransformerBlock)

ViTBlock(num_hiddens, mlp_num_hiddens, num_heads, dropout, use_bias=False, rngs)

Pre-norm block with LayerNorm and an exact-GELU MLP. Abschnitt 11.5

class Vocab

Vocab(tokens=(), min_freq=0, reserved_tokens=())

Vocabulary for text. Abschnitt 8.2

  • to_tokens(indices)
  • unk()

class WikiText103(d2l.DataModule)

WikiText103(batch_size, num_steps, num_train=None, num_val=None)

WikiText-103 as UTF-8 bytes, cut into windows of num_steps bytes. Abschnitt 9.5

  • windows(corpus, starts) — Inputs and next-byte targets of the windows at starts.
  • train_dataloader()
  • val_dataloader()

class Accumulator

Accumulator(n)

For accumulating sums over n variables. Abschnitt 39.9

  • add(*args)
  • reset()

class Animator

Animator(xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1, figsize=(3.5, 2.5))

For plotting data in animation. Abschnitt 39.9

  • add(x, y)

class ArrayData(d2l.DataModule)

ArrayData(X, y, batch_size=64)

Minibatches of the arrays X and y; training batches are shuffled. Abschnitt 4.5

  • get_dataloader(train)

class ArrayLoader

ArrayLoader(arrays, batch_size, shuffle=False, drop_last=False)

Minibatches of in-memory arrays, reshuffled each pass if shuffle. Abschnitt 2.4

class Averager

Example-weighted means of batch metrics, summed on the device. Abschnitt 2.4

  • add(metrics, n)
  • mean() — One host synchronization per metric; the loss comes first.

class BPETokenizer

BPETokenizer(vocab_size=1024, pattern=None, specials=('<pad>', '<bos>', '<eos>'))

Byte-level BPE tokenizer trained by iterated most-frequent-pair Abschnitt 8.2

  • pad()
  • bos()
  • eos()
  • train(text) — Learn vocab_size - 256 merges, most frequent pair first. Abschnitt 8.2
  • encode(text, allow_special=False)
  • decode(ids)
  • from_tiktoken(name) — Load a published bytes->rank table (e.g. ‘gpt2’) into our encoder. Abschnitt 8.2

class BananasDataset(gluon.data.Dataset)

BananasDataset(is_train)

A customized dataset to load the banana detection dataset. ?sec-object-detection-dataset

class Benchmark

Benchmark(f, warmup=3, repeats=10, desc='time')

Time a callable: warmup, then device-synchronized average seconds. Abschnitt 5.7

class Classifier(d2l.Module)

The base class of classification models. Abschnitt 3.3

  • validation_step(batch)
  • accuracy(Y_hat, Y, averaged=True) — Compute the fraction of correct predictions. Abschnitt 3.3
  • loss(Y_hat, Y, averaged=True)
  • layer_summary(X_shape)

class DataModule(d2l.HyperParameters)

DataModule(root='../data', num_workers=4)

The base class of data. Abschnitt 2.4

  • get_dataloader(train)
  • train_dataloader()
  • val_dataloader()
  • get_tensorloader(tensors, train, indices=slice(0, None))

class FashionMNIST(d2l.DataModule)

FashionMNIST(batch_size=64, resize=(28, 28))

The Fashion-MNIST dataset. Abschnitt 3.2

  • read(train) — Images and labels of one split, read from the published files.
  • to_dataset(images, labels) — Convert all images at once: channel axis first, values in [0, 1].
  • text_labels(indices) — Return text labels. Abschnitt 3.2
  • get_dataloader(train)
  • batchify(examples) — Stack examples into a minibatch and resize it if asked to. Abschnitt 3.2
  • visualize(batch, nrows=1, ncols=8, labels=None) — Show the images of a batch in grayscale, titled by their labels. Abschnitt 3.2

class HyperParameters

The base class of hyperparameters. Abschnitt 39.9

  • save_hyperparameters(ignore=None) — Save function arguments into instance attributes. Abschnitt 39.9

class LeNet(d2l.Classifier)

LeNet(lr=0.1, num_classes=10)

The layout of LeNet-5, with sigmoid activations and average pooling. Abschnitt 6.6

class LinearRegression(d2l.Module)

LinearRegression(lr)

Linear regression built from framework components. Abschnitt 2.5

  • loss(y_hat, y)
  • configure_optimizers()
  • get_w_b()

class LinearRegressionScratch(d2l.Module)

LinearRegressionScratch(num_inputs, lr, sigma=0.01)

The linear regression model implemented from scratch. Abschnitt 2.4

  • forward(X)
  • loss(y_hat, y)
  • configure_optimizers()

class MaskedSoftmaxCELoss(gluon.loss.SoftmaxCELoss)

The softmax cross-entropy loss with masks. Abschnitt 39.9

  • forward(pred, label, valid_len)

class Module(nn.Block, d2l.HyperParameters)

The base class of models. Abschnitt 2.4

  • loss(y_hat, y)
  • forward(X)
  • training_step(batch) — The mean loss on one minibatch, or a dict of batch-mean metrics
  • validation_step(batch) — The mean loss on one minibatch of validation data, or a dict of
  • configure_optimizers()

class ProgressBoard(d2l.HyperParameters)

ProgressBoard(xlabel=None, ylabel=None, xlim=None, ylim=None, xscale='linear', yscale='linear', figsize=(3.5, 2.5), display=True)

Curves that grow during training; show redraws them. Abschnitt 2.4

  • clear() — Forget all curves; the next show starts a new figure.
  • draw(x, y, label) — Append the point (x, y) to the curve called label.
  • show(final=True) — Redraw all curves; the book build renders only the final call. Abschnitt 39.9

class RNN(d2l.Module)

RNN(num_inputs, num_hiddens, sigma=0.01)

The RNN model implemented with high-level APIs. Abschnitt 8.4.6

  • forward(inputs, H=None)

class RNNLM(d2l.RNNLMScratch)

The RNN-based language model implemented with high-level APIs. Abschnitt 8.4.6

  • init_params()
  • embedding(X)
  • output_layer(hiddens)

class RNNLMScratch(d2l.Classifier)

RNNLMScratch(rnn, vocab_size, lr=0.01, dropout=0, emb_dropout=0)

The RNN-based language model implemented from scratch. Abschnitt 8.4.2

  • init_params()
  • validation_step(batch)
  • embedding(X)
  • output_layer(rnn_outputs)
  • forward(X, state=None)
  • predict(prefix, num_tokens, tok, device=None, temperature=0.0)

class RNNScratch(d2l.Module)

RNNScratch(num_inputs, num_hiddens, sigma=0.01)

The RNN model implemented from scratch. Abschnitt 8.4.2

  • forward(inputs, state=None)

class ResNeXtBlock(nn.HybridBlock)

ResNeXtBlock(num_channels, groups, bot_mul, use_1x1conv=False, strides=1)

The ResNeXt block. Abschnitt 7.4

  • forward(X)

class Residual(nn.HybridBlock)

Residual(num_channels, use_1x1conv=False, strides=1)

The Residual block of ResNet models. Abschnitt 7.4

  • forward(X)

class SGD(d2l.HyperParameters)

SGD(params, lr)

Minibatch stochastic gradient descent. Abschnitt 2.4

  • step(_)

class SoftmaxRegression(d2l.Classifier)

SoftmaxRegression(num_outputs, lr)

The softmax regression model. Abschnitt 3.3.5

  • forward(X)

class SyntheticRegressionData(d2l.DataModule)

SyntheticRegressionData(w, b, noise=0.01, num_train=1000, num_val=1000, batch_size=32)

Synthetic data for linear regression. Abschnitt 2.4

  • get_dataloader(train)

class TimeMachine(d2l.DataModule)

TimeMachine(batch_size, num_steps, num_train=50000, num_val=5000, tokenization='bpe', vocab_size=1024)

The Time Machine dataset. Abschnitt 8.2

  • build(raw_text, vocab=None)
  • get_dataloader(train)

class Timer

Record multiple running times. Abschnitt 9.2.2

  • start() — Start the timer.
  • stop() — Stop the timer and record the time in a list.
  • avg() — Return the average time.
  • sum() — Return the sum of time.
  • cumsum() — Return the accumulated time.

class Tracker(d2l.Trainer)

Tracker(max_epochs, datasets)

A Trainer that records the accuracy on named datasets every epoch. Abschnitt 4.5

  • validate()

class Trainer(d2l.HyperParameters)

Trainer(max_epochs, num_gpus=0, gradient_clip_val=0)

Fit a Module to a DataModule, keeping a per-epoch history. Abschnitt 2.4

  • prepare_data(data)
  • prepare_optimizer(model)
  • fit(model, data)
  • record(split, metrics, x)
  • fit_epoch()
  • validate()
  • evaluate(model, data, train=False) — Metrics of model on the validation data of data (on its training Abschnitt 3.3
  • prepare_batch(batch)
  • prepare_model(model)
  • clip_gradients(grad_clip_val, model)

class VOCSegDataset(gluon.data.Dataset)

VOCSegDataset(is_train, crop_size, voc_dir)

A customized dataset to load the VOC dataset. ?sec-semantic-segmentation

  • normalize_image(img)
  • filter(imgs)

class Vocab

Vocab(tokens=(), min_freq=0, reserved_tokens=())

Vocabulary for text. Abschnitt 8.2

  • to_tokens(indices)
  • unk()

39.10.2 Funktionen

accuracy

accuracy(y_hat, y)

Compute the number of correct predictions. Abschnitt 39.9

add_to_class

add_to_class(Class)

Register functions as methods in created class. Abschnitt 2.4

adjoint_scan

adjoint_scan(a, b)

All states of h_t = a_t * h_{t-1} + b_t, differentiated by a scan. Abschnitt 12.5

align_token_labels

align_token_labels(word_ids, word_labels, scheme='first')

Token labels from word labels; word_ids gives each token’s word ?sec-lm-bert

align_uniform

align_uniform(Zx, Zy, t=2.0, Zu=None)

Wang and Isola’s alignment, the mean squared distance between the ?sec-lm-text-embeddings

ancestral_sample

ancestral_sample(pred, x, path, steps, t_start=1.0)

Ho et al.’s sampler from x at t_start (1 is noise) to data at t = 0. Abschnitt 17.3

anisotropy

anisotropy(Z, n_pairs=200000, seed=0)

Mean cosine similarity between distinct rows of Z, over n_pairs ?sec-lm-text-embeddings

api_calls

api_calls(calls_path)

The live attempts in a client’s calls log (d2l.ChatAPI.calls_path) ?sec-lm-api

api_committed

api_committed(folders)

Totals over every arm in the manifest.json of each folder that has ?sec-lm-api

api_cost

api_cost(usage, price)

Cost in USD of one response, ((p - c) input + c cached_input + ?sec-lm-api

api_recorded

api_recorded(api)

Totals of a whole recording from a client’s calls log: live calls, ?sec-lm-api

api_unpack

api_unpack(key)

Download a registered zip (sha1 checked) and unpack it once, into a ?sec-lm-api

as_metrics

as_metrics(out)

A step returns a loss or a dict of metrics; return a dict. Abschnitt 2.4

assert_key_absent

assert_key_absent(roots, key)

Raise AssertionError if the bytes of key occur in any file under the ?sec-lm-api

assign_anchor_to_bbox

assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5)

Assign closest ground-truth bounding boxes to anchor boxes. ?sec-anchor

associative_recall

associative_recall(rng, batch_size, num_pairs, num_keys=512, num_values=4, num_steps=256, num_rebound=0, gap=None)

Key-value pairs, filler, then every key again as a query. The first Abschnitt 12.6

associative_scan

associative_scan(combine, elems)

All prefixes of elems under an associative combine; time is axis 1. Abschnitt 12.3

audit_removals

audit_removals(df, keep, by, ref=None, n_boot=2000, cluster=None, seed=0)

Removal rate per group of df[by] with a 95% percentile bootstrap ?sec-lm-quality-filtering

backoff_delay

backoff_delay(attempt, base=1.0, cap=60.0, rng=None, retry_after=None)

Full-jitter sleep after failed attempt attempt (0, 1, …): uniform ?sec-lm-api

barycentric

barycentric(W)

2-D coordinates of three-domain mixtures (n, 3) in the triangle with ?sec-lm-data-mixtures

batch_to_heads

batch_to_heads(Y, batch_size)

(batch_size * num_heads, T, e) -> (batch_size, T, num_heads * e). Abschnitt 12.6

batched

batched(f, X, batch_size=1000)

Apply f to X in batches, without gradients, and concatenate. Abschnitt 16.5

bbox_to_rect

bbox_to_rect(bbox, color)

Convert bounding box to matplotlib format. ?sec-bbox

benchmark_items

benchmark_items()

The test items of GSM8K (1,319), ARC-Challenge (1,172) and MMLU ?sec-lm-dedup

best_br

best_br(k, tau, w_fp=1.0, w_fn=1.0)

The (b, r) with b = k // r that minimizes the weighted error areas ?sec-lm-dedup

binarize

binarize(Z)

The signs of Z (N, m) as bits, eight per byte: uint8 (N, m / 8). ?sec-lm-text-embeddings

binary_f1

binary_f1(y, pred)

F1 of boolean predictions against boolean labels (0 if none). ?sec-lm-quality-filtering

bind_hf_kernels

bind_hf_kernels()

Route the linear-attention functions of Transformers’ Gated DeltaNet ?sec-lm-hf-models

bits_per_byte

bits_per_byte(model, tokenizer, texts, ctx_len=2048, stride=None, batch_size=4)

Bits per UTF-8 byte of texts: total negative log-likelihood in nats ?sec-lm-scoring

bleu

bleu(pred_seq, label_seq, k)

Compute the BLEU. Abschnitt 12.2.2

block_runs

block_runs(cells, classes)

(block, class) cells as text, runs of blocks per class in the order ?sec-lm-interpretability

bm25_tokenize

bm25_tokenize(text, split_identifiers=True)

Lower-cased words and numbers of text; an identifier such as ?sec-lm-retrieval

book_corpus

book_corpus(chunking='sections', size=256, overlap=0, source='hub', root=os.path.join('..', 'data', 'lm'))

The book corpus (artifact lm-book-r3-v1) under one chunking: ?sec-lm-retrieval

book_qa

book_qa(split='dev', answerable=None, types=None, n=None, seed=0, root=os.path.join('..', 'data', 'lm'))

The book’s question set (artifact lm-book-qa-v2), one split: a ?sec-lm-rag

bootstrap_ci

bootstrap_ci(scores, n_boot=10000, cluster=None, seed=0, alpha=0.05)

Percentile bootstrap interval for the mean of scores. With cluster ?sec-lm-eval-suites

box_center_to_corner

box_center_to_corner(boxes)

Convert from (center, width, height) to (upper-left, lower-right). ?sec-bbox

box_corner_to_center

box_corner_to_center(boxes)

Convert from (upper-left, lower-right) to (center, width, height). ?sec-bbox

box_iou

box_iou(boxes1, boxes2)

Compute pairwise IoU across two lists of anchor or bounding boxes. ?sec-anchor

bpb_from_nll

bpb_from_nll(sum_nll_nats, n_bytes)

Bits per byte from a summed negative log-likelihood in nats and the ?sec-lm-data-mixtures

bradley_terry

bradley_terry(winners, losers, n_items, weights=None, l2=0.001, n_iter=50)

Bradley-Terry strengths s, P(i beats j) = sigmoid(s_i - s_j): the ?sec-lm-eval-suites

build_array_nmt

build_array_nmt(lines, vocab, num_steps)

Transform text sequences of machine translation into minibatches. Abschnitt 39.9

bytes_read

bytes_read(config, n, b=2)

Bytes a decode step reads at context n: the weights except the ?sec-lm-hf-models

c0_documents

c0_documents(manifest='lm-c0-docs-v1', cache_dir=None)

The c0 documents: the cached rebuild in cache_dir (default ?sec-lm-quality-filtering

cache_bytes

cache_bytes(cache)

Bytes of the floating-point tensors reachable from a cache object, ?sec-lm-hf-models

cache_stream

cache_stream(model, windows, layer, batch=32)

The stream after block layer at the positions >= 1 of windows ?sec-lm-interpretability

calibrate_labels

calibrate_labels(logprobs, content_free_logprobs)

Contextual calibration: subtract the mean log-probabilities (M, L) ?sec-lm-prompting

campaign_record

campaign_record(spec, result, cfg)

The JSON record a finished proxy run leaves in a campaign file: its ?sec-lm-data-mixtures

causal_mask

causal_mask(num_queries, num_keys=None, device=None)

Boolean (queries, keys) mask, True where a query may see a key. Abschnitt 10.2

ce_loss

ce_loss(model, X, Y)

Mean cross-entropy of the logits model(X) for the labels Y. Abschnitt 9.8

cfg

cfg(net, c, gamma)

Classifier-free guidance: (x, t) -> u + gamma (u_c - u), u unlabeled. Abschnitt 17.4

char_fraction

char_fraction(text, pattern)

The fraction of the non-space characters of text that match the ?sec-lm-interpretability

char_ngram_f1

char_ngram_f1(a, b, n=5)

(precision, recall, F1) of the character n-grams of text a against ?sec-lm-crawl

chat_batch

chat_batch(api, requests, concurrency=8)

Send requests (dicts with ‘messages’, optionally ‘replica’ and request ?sec-lm-api

chat_thinks

chat_thinks(r)

Whether a chat result reasoned: reasoning tokens in its usage, or ?sec-lm-api

check_closed_loop

check_closed_loop(results, c)

Raise ValueError unless results can be one closed loop of c recorded ?sec-lm-api

check_shape

check_shape(a, shape)

Check the shape of a tensor. Abschnitt 8.4.2

choose_mixture

choose_mixture(f, target, n_grid=5000, seed=0, max_weight=0.9, within=None)

The mixture w with no weight above max_weight that minimizes the ?sec-lm-data-mixtures

chrf

chrf(pred, label, n=6, beta=2)

chrF (Popovic, 2015): character n-gram F-score. Abschnitt 12.2.2

chunk_doc

chunk_doc(token_ids, tokenizer, max_tokens=400)

Split a document’s token ids into chunks of at most max_tokens ids: ?sec-lm-synthetic-data

chunked_delta_rule

chunked_delta_rule(Q, K, V, beta, log_a, chunk_size)

Outputs y_t = S_t q_t of the gated delta rule, computed in chunks. Abschnitt 12.7

chunked_linear_attention

chunked_linear_attention(Q, K, V, log_a, chunk_size)

y_t = S_t q_t with S_t = a_t S_{t-1} + v_t k_t^T, computed in chunks. Abschnitt 12.6

classify_failure

classify_failure(result, item, judge_out, corpus, depth=50)

The stage at which an answer failed: ‘correct’; an unanswerable item ?sec-lm-rag-fixes

clean_ag_news

clean_ag_news(titles)

AG News titles with the escapes left in them resolved: HTML ?sec-lm-prompting

clipped_surrogate

clipped_surrogate(rho, adv, epsilon)

PPO’s per-sample objective eq_ppo_clip: min(rho A, clip(rho) A). Abschnitt 15.2

closed_loop_stats

closed_loop_stats(results, c)

Throughput and latency of a closed loop that kept c requests in ?sec-lm-api

cluster_resample

cluster_resample(clusters, n_boot=2000, seed=0)

Per replicate, the item indices of a resample of whole clusters ?sec-lm-interpretability

cohen_kappa

cohen_kappa(a, b)

Cohen’s kappa of two label arrays: agreement beyond what the two ?sec-lm-quality-filtering

collapse_sim

collapse_sim(n, generations, mode='replace', reps=1000, seed=0, mu=0.0, sigma=1.0)

The Gaussian refit: generation 0 is N(mu, sigma^2); fit t (t >= 1) ?sec-lm-synthetic-data

collect_hiddens

collect_hiddens(model, input_ids)

Per layer, in execution order: the attention output, the residual ?sec-lm-d2l-checkpoint

conditional

conditional(net, c)

The field (x, t) -> net(x, t, c) with the labels c fixed. Abschnitt 17.4

config_memory

config_memory(config, seq_len, batch_size, dtype_bytes=2, state_bytes=4, conv_bytes=None, conv_taps=None, window_cached=None, include_vision=False, include_mtp=False, logits_to_keep=1)

Bytes to run a model on batch_size sequences of seq_len tokens. ?sec-lm-hf-models

config_params

config_params(config, include_vision=False, include_mtp=False, by_group=False)

Parameters of a dense or hybrid model (Qwen3, Qwen3.5, Gemma 4), ?sec-lm-hf-models

containment

containment(a, b)

The containment |A & B| / |A| of A in B (Broder); 0 if A is empty. ?sec-lm-dedup

contam_documents

contam_documents(plants, stream)

The documents of the planted set, doc_id -> text: each planted text ?sec-lm-dedup

cooccurrence_counts

cooccurrence_counts(corpus, vocab_size, window=5, weighting='uniform')

Word-context counts within window positions as a symmetric ?sec-lm-word-embeddings

copyfile

copyfile(filename, target_dir)

Copy a file into a target directory. ?sec-kaggle-cifar10

corr2d

corr2d(X, K)

Compute 2D cross-correlation. Abschnitt 6.2

corrupt

corrupt(y, fraction, rng)

Replace each label, with probability fraction, by a random class. Abschnitt 4.5

cosine_warmup

cosine_warmup(t, num_steps, warmup_steps)

Learning-rate factor: linear warmup from 0, then a half-cosine to 0. Abschnitt 7.1

cost_of_half

cost_of_half(cost, sw)

The cost at which a strength grid (cost and switched fraction per ?sec-lm-interpretability

cost_per_example

cost_per_example(n_params, n_tokens, n_embed=0)

Forward FLOPs per example, 2 (n_params - n_embed) n_tokens: a ?sec-lm-bert

cov_at_budget

cov_at_budget(ranked_chunk_ids, item, corpus, budget_tokens)

Whether the chunks of corpus taken in rank order until the next one ?sec-lm-rag

cpu

cpu()

Get the CPU device. Abschnitt 5.7

critic_step

critic_step(net_D, opt_D, loss_D, real, fake, gamma, y=None)

One critic step on loss_D + gamma/2 (R1 + R2); return the loss and Abschnitt 16.4

cuda_graphed

cuda_graphed(step, device, warmup=3)

Return a function that calls step(). On a CUDA device it runs step() Abschnitt 16.4

ddim_invert

ddim_invert(pred, x, path, steps, t_end=1.0)

Deterministic DDIM run backwards, from data x at t = 0 to t_end. Abschnitt 17.5

ddim_sample

ddim_sample(pred, x, path, steps, eta=0.0, t_start=1.0, t_end=0.0)

DDIM from x at t_start (1 is noise) to t_end; eta = 0 is deterministic. Abschnitt 17.5

decay_mask

decay_mask(log_a)

L[t, s] = a_{s+1} * … * a_t for s <= t, and 0 for s > t. Abschnitt 12.6

decode_body

decode_body(body, headers)

(text, charset, source) of an HTTP payload. The charset comes from ?sec-lm-crawl

delayed_recall

delayed_recall(rng, batch_size, num_steps, num_symbols=8, blank_fillers=False)

A symbol, then num_steps - 1 fillers; the target is the symbol. Abschnitt 12.1.4

delta_rule_writes

delta_rule_writes(K, V, beta, log_a)

W and Z with corrected values U = W - Z S_0^T, for every chunk. Abschnitt 12.7

detect_lang

detect_lang(text, k=1)

The top k (language, score) pairs of fastText’s 176-language ?sec-lm-crawl

detection_stats

detection_stats(y, score, threshold)

Precision and recall of score > threshold as a detector of the ?sec-lm-interpretability

distinct_n

distinct_n(texts, n=4)

The share of distinct word n-grams among all word n-grams of texts ?sec-lm-synthetic-data

docs_hash

docs_hash(docs)

SHA-256 over the sorted (id, SHA-256 of the text) pairs: the content ?sec-lm-crawl

doremi_weights

doremi_weights(ref_model, proxy_model, domain_batches, steps, cfg, eta=1.0, smooth=0.001, lr=None)

DoReMi’s domain weights: train proxy_model on the alpha-weighted ?sec-lm-data-mixtures

download

download(url, folder='../data', sha1_hash=None)

Download a file to folder and return the local filepath. Abschnitt 39.9

download_extract

download_extract(name, folder=None)

Download and extract a zip/tar file. Abschnitt 39.9

download_keyed

download_keyed(key, root=os.path.join('..', 'data', 'lm'))

Download DATA_HUB[key] into root/key/ and return its local path. ?sec-lm-scoring

drop_path

drop_path(Y, p, training)

Zero each example of Y with probability p, rescale the rest. Abschnitt 7.6

edm_grid

edm_grid(steps, sigma_max=80.0, sigma_min=0.002, rho=7)

Karras et al.’s levels sigma_bar: even in sigma_bar^(1/rho), then 0. Abschnitt 17.5

edu_label_scores

edu_label_scores(model, tokenizer, prompts, batch_size=16, max_batch_tokens=24576, prefix='Educational score: ', extra_space=False)

(len(prompts), 6) float64: the probabilities of the next tokens ?sec-lm-quality-filtering

edu_label_scores_served

edu_label_scores_served(urls, tokenizer, prompts, model=None, prefix='Educational score: ', extra_space=False, concurrency=1)

edu_label_scores computed by OpenAI-compatible vLLM servers at urls, ?sec-lm-quality-filtering

edu_label_servers

edu_label_servers(gpus=None, vllm=None)

One d2l.LocalChatServer per GPU (default: every visible GPU), each ?sec-lm-quality-filtering

effective_tokens

effective_tokens(unique, epochs, r_star=15.4)

Effective data D’ = U + U R* (1 - exp(-R / R*)) of epochs passes ?sec-lm-data-mixtures

embed_docs

embed_docs(texts, model_id='Qwen/Qwen3-Embedding-0.6B', max_len=512, batch=64, pool='last', device=None)

(len(texts), d) float16 unit vectors of documents under a frozen ?sec-lm-quality-filtering

embed_texts

embed_texts(model, tokenizer, texts, pooling='mean', batch_size=64, max_len=512, normalize=True, prefix='', padding_side=None, device=None)

Vectors (N, m), float32 on the CPU, of prefix + text for each text: ?sec-lm-text-embeddings

epsilon_greedy

epsilon_greedy(q, epsilon, rng)

Explore with probability epsilon, else act greedily on the values q. Abschnitt 14.3

evaluate

evaluate(env, policy, num_episodes, gamma=1.0, rng=None)

Mean discounted return of an acting policy over Monte Carlo episodes. Abschnitt 14.2

evaluate_accuracy

evaluate_accuracy(model, batches)

Fraction of the examples in batches that model classifies correctly. Abschnitt 9.5

evaluate_accuracy_gpu

evaluate_accuracy_gpu(net, data_iter, device=None)

Compute the accuracy for a model on a dataset using a GPU. Abschnitt 39.9

evaluate_loss

evaluate_loss(net, data_iter, loss)

Evaluate the loss of a model on the given dataset. Abschnitt 39.9

extend_vocab

extend_vocab(model, tokenizer, new_pieces, init='random', seed=0)

Add new_pieces to a Transformers tokenizer (as added tokens, which ?sec-lm-tokenizers

extract

extract(filename, folder=None)

Extract a zip/tar file into folder. Abschnitt 39.9

extract_answer

extract_answer(text, kind='gsm8k', strict=False)

The answer a generated text commits to, as a string, or None. ?sec-lm-scoring

extract_page

extract_page(job)

The extract cell’s worker for one HTML response job = (path, offset, ?sec-lm-crawl

extract_text

extract_text(html, method='trafilatura', url=None)

The main text of a page, or None. ‘naive’: blocks with at least 40 ?sec-lm-crawl

f_valley

f_valley(x1, x2)

The ill-conditioned quadratic valley h1/2 x1^2 + h2/2 x2^2, with Abschnitt 9.1

fan_in_init

fan_in_init(module)

Fan-in normal weights with the leaky-ReLU gain, zero offsets. Abschnitt 16.5

fashion_feature_cnn

fashion_feature_cnn(X, y)

The feature network that judges Fashion-MNIST samples in this chapter. Abschnitt 17.4

fd_features

fd_features(cnn, imgs)

Features of gray images (n, 1, 28, 28) in [-1, 1], on the CPU. Abschnitt 17.4

fertility_table

fertility_table(encoders, parallel, ref='eng_Latn')

Per encoder and language: passages, UTF-8 bytes, tokens, bytes per ?sec-lm-tokenizers

fetch_warc_range

fetch_warc_range(pin='lm-cc-warc-256m-v1', n_bytes=None, cache_dir=None, which='warc')

Local path of the pinned Common Crawl bytes: which=‘warc’ gives the ?sec-lm-crawl

fewshot_prompt

fewshot_prompt(demos, query, template='plain', fmt=None, label_map=None, system=None)

Demonstrations demos, a list of (x, y), and a query x as a prompt. ?sec-lm-prompting

fid_score

fid_score(feat_p, feat_q)

Frechet distance between Gaussians fitted to two feature sets. Abschnitt 16.5

final_loss

final_loss(losses, k=100)

Mean of the last k losses; infinity if the run diverged. Abschnitt 9.5

finetune_classifier

finetune_classifier(model, train, eval, lr, epochs, batch_size, seed, warmup=0.1, device=None)

Fine-tune model on train, a list of (input_ids, label) or, for token ?sec-lm-bert

first_divergence

first_divergence(errors, floor, factor=10.0)

The first (layer, capture point) in execution order whose median ?sec-lm-d2l-checkpoint

fit_mixture_regression

fit_mixture_regression(W, L, kind='ridge', **kw)

A predictor f(w) -> per-domain losses fitted on mixtures W (n, m) ?sec-lm-data-mixtures

fit_quality_head

fit_quality_head(X, y, kind='regression', epochs=200, lr=0.001, weight_decay=0.0, seed=0)

A linear head on fixed features, full-batch AdamW: kind=‘regression’ ?sec-lm-quality-filtering

fit_value

fit_value(ac, obs, target, num_steps=1)

Regress the value head on a fixed target: eq_value_baseline for nets. Abschnitt 14.9

flow_map_error

flow_map_error(u, teacher, x0, eps, s, t)

Per-example squared error of the average velocity u(x_t, s, t) against Abschnitt 17.8

flow_map_sample

flow_map_sample(u, x, steps, t_start=1.0)

Jump from x at t_start (1 is noise) to data at t = 0 in equal steps. Abschnitt 17.8

fmt_ci

fmt_ci(mean, ci, digits=3)

A value and its interval as text: ‘mean [lo, hi]’. ?sec-lm-interpretability

format_mc

format_mc(question, options, fmt='cloze', shots=())

A multiple-choice item as (prompt, choices). ‘cloze’: the prompt ?sec-lm-scoring

frontier_area

frontier_area(cost, sw, cap)

The area under the frontier from cost 0 to cap (linear between the ?sec-lm-interpretability

frontier_envelope

frontier_envelope(cost, sw)

The monotone envelope of the points (cost, sw): the most switched at ?sec-lm-interpretability

fwedu_bucket

fwedu_bucket(doc_id)

The bucket (0-255) of a FineWeb-Edu document: the first 32 bits of ?sec-lm-data-mixtures

fwedu_shards

fwedu_shards(which='100m', fetch=True, max_tokens=None)

The reference shards of FineWeb-Edu under the reference tokenizer: ?sec-lm-tokenizers

gan_loss_D

gan_loss_D(critic, real, fake)

Logistic critic loss -E[log sigma(D(x))] - E[log sigma(-D(x’))]: the Abschnitt 16.4

gan_loss_G

gan_loss_G(critic, real, fake)

Non-saturating generator loss -E[log sigma(D(x’))]; real is unused. Abschnitt 16.4

gd_2d

gd_2d(x1, x2, s1, s2, f_grad, eta)

One step of gradient descent in 2D; the state stays zero. Abschnitt 9.1

gelu_ish

gelu_ish(x)

The tanh approximation of GELU with rounded constants: a chain of Abschnitt 13.1

generate

generate(model, tokenizer, prompts, max_new_tokens=None, strategy='greedy', temperature=1.0, k=None, p=None, min_p=None, seed=0, eos_token_ids=None, stop=None, chat=False, enable_thinking=None, return_logprobs=False, batch_size=8)

Continue each prompt (a string, or with chat=True also a list of ?sec-lm-d2l-checkpoint

generator_step

generator_step(net_G, opt_G, loss_G, net_D, real, z, y=None)

One generator step on loss_G against the critic; return the loss. Abschnitt 16.4

get_airfoil

get_airfoil(batch_size=10, n=1500)

Load the standardized airfoil self-noise data as minibatches. Abschnitt 9.2.2

get_dataloader_workers

get_dataloader_workers()

Use 4 processes to read the data. Abschnitt 39.9

get_fashion_mnist_labels

get_fashion_mnist_labels(labels)

Return text labels for the Fashion-MNIST dataset. Abschnitt 39.9

gpt2_tokenizer

gpt2_tokenizer()

GPT-2’s byte-level BPE tokenizer, assembled by tiktoken. Abschnitt 11.2

gpu

gpu(i=0)

Get a GPU device. Abschnitt 5.7

grad_clipping

grad_clipping(net, theta)

Clip the gradient. Abschnitt 39.9

grad_sq_norm

grad_sq_norm(model, X, Y)

Squared norm of the gradient of ce_loss over all parameters. Abschnitt 9.8

gradient_penalty

gradient_penalty(D, X, fake, u, one_sided=False)

Mean (|D’(x)| - 1)^2 at the points u X + (1 - u) fake (inputs 1-D); Abschnitt 16.2

group_step

group_step(task, theta, K, reward, rng, lr=2.0)

verifier_step with the group-normalized weight (GRPO): the rewards Abschnitt 14.8

hamming_scores

hamming_scores(Qbits, Dbits)

The number of equal bits of each packed query and each packed ?sec-lm-text-embeddings

heads_to_batch

heads_to_batch(Z, num_heads)

(batch_size, T, num_heads * e) -> (batch_size * num_heads, T, e). Abschnitt 12.6

heun_sample

heun_sample(pred, x, sigma_bars)

Heun on d x_bar / d sigma_bar = eps: an Euler trial, then the average Abschnitt 17.5

heuristic_filters

heuristic_filters(text, cfg=None)

The reason codes of the rules in cfg (default GOPHER_CFG) that fire ?sec-lm-quality-filtering

hf_attention

hf_attention(config, device)

The attention that runs config on device without an n x n mask: ?sec-lm-hf-models

hf_capacity

hf_capacity(model, config, ids, budget, n=4096)

The largest batch at n tokens (doubling, then bisection) and the ?sec-lm-hf-models

hf_compare_kernels

hf_compare_kernels(model, config, ids, contexts, decode_at=4096, positions=64)

A prefill on the fused kernels and inside reference_kernels, per ?sec-lm-hf-models

hf_decode_ms

hf_decode_ms(model, cache, token, steps=64, warmup=3, repeats=10)

Median, first and third quartile of milliseconds per greedy decode ?sec-lm-hf-models

hf_kernels

hf_kernels(model)

The code a model’s attention and Gated DeltaNet layers run on a GPU ?sec-lm-hf-models

hf_measure

hf_measure(model, config, ids, beta, contexts=(256, 1024, 4096, 16384))

Memory and decode time at each context, one row (dict) per context: ?sec-lm-hf-models

hf_memory_table

hf_memory_table(rows)

The memory columns of hf_measure’s rows: the walker’s bytes and the ?sec-lm-hf-models

hf_prefill

hf_prefill(model, ids, n, keep=1)

Prefill the first n tokens: the output, the allocated bytes before, ?sec-lm-hf-models

hf_profile_steps

hf_profile_steps(model, ids, rows)

Add one decode step’s device time (busy and matrix products) and ?sec-lm-hf-models

hf_step_kernels

hf_step_kernels(model, cache, token, steps=10)

Device milliseconds per kernel of one decode step, and the number of ?sec-lm-hf-models

hf_time_table

hf_time_table(rows, beta_sheet)

The time columns of the profiled rows, in ms per decode step: wall ?sec-lm-hf-models

host_class

host_class(url)

A coarse class of the host (edu_gov, wiki, forum, news, blog, shop, ?sec-lm-crawl

html_skeleton

html_skeleton(html, n=25)

The first n elements of a page’s <body> as indented tag names, each ?sec-lm-crawl

html_structure

html_structure(html)

The structural content of a page, read from its HTML alone (no ?sec-lm-crawl

info_nce_loss

info_nce_loss(q, d, tau=0.05, hard_neg=None, symmetric=False)

InfoNCE with in-batch negatives for unit vectors q, d (B, m), row i ?sec-lm-text-embeddings

init_cnn

init_cnn(module)

Initialize weights for CNNs. Abschnitt 6.6

init_distributed

init_distributed()

Join the process group of torchrun; return the rank, the number of Abschnitt 13.6

init_lecun

init_lecun(module)

LeCun normal weights and zero biases for all linear, convolutional, Abschnitt 12.1.4

init_timescales

init_timescales(layer, dt_min=0.001, dt_max=0.1)

Start a minGRU’s gates at the decays exp(-dt) of S4D. Abschnitt 12.4

intervene

intervene(model, sites=None, record=(), record_grad=False, stop_after=None)

Context manager over a d2l.GPT that overwrites the sites (kind, ?sec-lm-interpretability

item_seed

item_seed(seed, task_id, item_id)

A 63-bit seed for one item’s random draws, from sha256 of ?sec-lm-eval-suites

iter_warc

iter_warc(source, n_bytes=None, types=('response',), stats=None)

Yield the WARC records of the given types (None: all) from a local ?sec-lm-crawl

jaccard_exact

jaccard_exact(a, b)

The resemblance |A & B| / |A | B| of two shingle collections taken ?sec-lm-dedup

js_mixtures

js_mixtures(mus_q, As_q, mus_p=mu_p, As_p=A_p)

JS(p, q) between two known mixtures, p the data by default, by Abschnitt 16.2

json_agreement

json_agreement(new, old)

How far two JSON-like results agree: the number of leaf values in ?sec-lm-crawl

judge_pairwise

judge_pairwise(judge, tokenizer, question, answer_a, answer_b, rubric=JUDGE_RUBRIC_V1, batch_size=8, max_batch_tokens=None, return_mass=False)

Ask a chat model which answer is better, once with answer_a in the ?sec-lm-eval-suites

kernel_times

kernel_times(f, steps=10)

Device milliseconds per call of f, for every kernel that f runs. Abschnitt 13.1

kid_score

kid_score(feat_p, feat_q)

Unbiased MMD^2 between two feature sets, cubic polynomial kernel. Abschnitt 16.5

kmeans

kmeans(X, n_clusters, n_iter=20, seed=0)

Lloyd’s k-means of the rows of X from a seeded k-means++ start: ?sec-lm-retrieval

kneser_ney

kneser_ney(train, tokens, vocab_size, n=3)

Interpolated Kneser-Ney log-probabilities (nats) of each of tokens. Abschnitt 8.3

kv_cache_bytes

kv_cache_bytes(model, num_tokens, batch_size=1, bytes_per_elem=4)

Bytes of the keys and values of num_tokens positions in every block Abschnitt 11.3

label_logprobs

label_logprobs(model, tokenizer, prompts, label_words, batch_size=8, chat=False, enable_thinking=False, sep=None)

Log-probabilities (len(prompts), len(label_words)), float32 on the ?sec-lm-prompting

label_token_ids

label_token_ids(tokenizer, prompts, label_words, sep=None)

The prompts’ token ids, and per prompt the id of each label word’s ?sec-lm-prompting

langevin

langevin(score_fn, x, step, num_steps)

Langevin steps x <- x + step / 2 * score + sqrt(step) * noise. Abschnitt 17.1

layer_errors

layer_errors(ref, ours, skip_first=1)

Relative Frobenius error of each capture of collect_hiddens against a ?sec-lm-d2l-checkpoint

lcp_array

lcp_array(ids, sa)

lcp[i] = the length of the longest common prefix of the suffixes ?sec-lm-dedup

linear_scan

linear_scan(a, b, h0=None)

All states of h_t = a_t * h_{t-1} + b_t; time is the second axis. Abschnitt 12.3

linear_schedule

linear_schedule(start, end, num_steps)

step -> value, interpolated from start to end, then held at end. Abschnitt 14.3

linreg

linreg(X, w, b)

The linear regression model. Abschnitt 39.9

listing_endpoint

listing_endpoint(listing, model_id, provider)

The endpoint row of one provider of model_id in an OpenRouter listing ?sec-lm-api

lm_artifact

lm_artifact(key, rerun_name=None, rerun_dir=os.path.join('..', 'data', 'lm', 'rerun'))

Where a measured result is read from: rerun_dir/rerun_name, the file ?sec-lm-scoring

lm_doc_ce

lm_doc_ce(model, docs, prefix_ids=(), mask=None, batch=16)

Per document of docs (N, T), after the tokens prefix_ids: the mean ?sec-lm-interpretability

lm_free

lm_free()

Return the memory of deleted models to the GPU. ?sec-lm-scoring

lm_hub_rows

lm_hub_rows(repo, path, revision, start, stop, column='text')

Rows start, …, stop - 1 of one column of a parquet file of a Hub ?sec-lm-interpretability

lm_load_sae

lm_load_sae(key, device=None)

The TopKSAE that lm_save_sae wrote, registered as DATA_HUB[key], ?sec-lm-interpretability

lm_peak

lm_peak()

Peak GPU memory since the last call, as text: what tensors held, and ?sec-lm-scoring

lm_perplexity

lm_perplexity(model, batches)

Perplexity of a language model on the minibatches (X, Y) of batches. Abschnitt 9.5

lm_registered

lm_registered(key)

Local path of the registered artifact DATA_HUB[key], or None while ?sec-lm-scoring

lm_rerun

lm_rerun(artifacts)

The measured results this run regenerates, from the environment ?sec-lm-scoring

lm_round_robin

lm_round_robin(stride, first=0, blocks=20, block=1000)

Row i of each of the blocks at first + b * stride, then row i + 1. ?sec-lm-interpretability

lm_save_rerun

lm_save_rerun(name, write, rerun_dir=os.path.join('..', 'data', 'lm', 'rerun'))

Call write(path) for a regenerated artifact in rerun_dir and print ?sec-lm-scoring

lm_save_sae

lm_save_sae(sae, tokens, name)

Write sae in fp16, with its config and its training-token count, as ?sec-lm-interpretability

lm_save_table

lm_save_table(name, df, on, key, rerun_dir=os.path.join('..', 'data', 'lm', 'rerun'))

Write a regenerated table to rerun_dir/name (parquet, or JSON lines ?sec-lm-eval-suites

lm_stream

lm_stream(model, docs, site, batch=16)

The activation at site (recorded by d2l.intervene, which stops the ?sec-lm-interpretability

lm_walk_docs

lm_walk_docs(encode, source, rows, subsets, block=1000)

Visit the rows of source = (repo, path, revision) in the order rows ?sec-lm-interpretability

lm_word_features

lm_word_features(model, tokenizer, sentences, layer, batch=32)

Per word of sentences (read_conllu’s), at its last token: the token ?sec-lm-interpretability

lm_write_zip

lm_write_zip(path, members)

A zip archive of members (name -> bytes), byte-identical for ?sec-lm-interpretability

load_array

load_array(data_arrays, batch_size, is_train=True)

Construct a PyTorch data iterator. Abschnitt 39.9

load_checkpoint

load_checkpoint(path, model, optimizer=None, rng=None)

Restore the state written by save_checkpoint; return the raw dict. Abschnitt 5.6

load_cifar10_arrays

load_cifar10_arrays()

CIFAR-10 on the GPU if there is one, pixel values scaled to [-1, 1]. Abschnitt 39.9

load_data_bananas

load_data_bananas(batch_size)

Load the banana detection dataset. ?sec-object-detection-dataset

load_data_fashion_mnist

load_data_fashion_mnist(batch_size, resize=None)

Download the Fashion-MNIST dataset and then load it into memory. Abschnitt 39.9

load_data_nmt

load_data_nmt(batch_size, num_steps, num_examples=600)

Return the iterator and the vocabularies of the translation dataset. Abschnitt 39.9

load_data_voc

load_data_voc(batch_size, crop_size)

Load the VOC semantic segmentation dataset. ?sec-semantic-segmentation

load_encoder

load_encoder(model_id, revision=None, head=None, num_labels=None, dtype=torch.bfloat16, device=None, attn_implementation='sdpa', padding_side=None)

A pinned encoder from the Hugging Face Hub and its tokenizer, in eval ?sec-lm-bert

load_fashion_mnist_pm1

load_fashion_mnist_pm1(binary=False)

Fashion-MNIST (X, y, X_test, y_test), images in [-1, 1] or binary. Abschnitt 17.1

load_gpt2

load_gpt2()

GPT-2 small (124M) as a GPT with the released weights, in eval Abschnitt 11.2

load_hf

load_hf(model_id, revision=None, dtype=torch.bfloat16, device_map='auto', attn_implementation=None)

A pinned causal language model from the Hugging Face Hub, text part ?sec-lm-hf-models

load_pokemon

load_pokemon(resolution=64)

All Pokemon sprites as one (n, 3, h, w) tensor in [-1, 1]. Abschnitt 16.5

load_pool

load_pool(path_or_key, name=None)

A token pool: a flat array of token ids (read-only memmap; every ?sec-lm-data-mixtures

load_qwen3

load_qwen3(model_id='Qwen/Qwen3-0.6B', revision=None, dtype=torch.bfloat16, device=None)

A pinned Qwen3 checkpoint from the Hugging Face Hub as a Qwen3GPT in ?sec-lm-d2l-checkpoint

load_qwen_scope_sae

load_qwen_scope_sae(repo_id, layer, revision=None, device=None, dtype=torch.float32, center=False)

The TopKSAE of one layer of a Qwen-Scope repository, downloaded ?sec-lm-interpretability

logit_lens

logit_lens(model, hidden)

The model’s final norm and output head applied in fp32 to hidden ?sec-lm-interpretability

long_csv

long_csv(T, axes, column)

The array T as CSV bytes, one row per entry: per axis a column that ?sec-lm-interpretability

loss_by_position

loss_by_position(model, data)

Mean validation loss in nats at each position of the window. Abschnitt 12.1.4

lr_sweep

lr_sweep(make_model, make_optimizer, data, lrs, seed, num_steps=2000, evaluate=None, metric='score', every=None, verbose=True)

Train make_model() with make_optimizer(model, lr) for each lr, from Abschnitt 9.5

lsh_candidates

lsh_candidates(sigs, b, r, max_bucket=1000, seed=0)

Candidate pairs (i, j), i < j, of signatures (a sequence of arrays, ?sec-lm-dedup

make_critic

make_critic()

Leaky-ReLU MLP with LeCun-normal weights and zero biases. Abschnitt 16.2

make_dup_pairs

make_dup_pairs(docs, spec, seed=0)

The labelled pairs of spec from docs (a DataFrame with id, url, text ?sec-lm-dedup

make_mlp

make_mlp(sizes, act)

Linear layers of the given widths with the activation module act Abschnitt 16.1

make_plants

make_plants(items, stream, paraphrase, n_per=100, n_controls=1000, seed=0, min_words=13, max_words=180, prompt_sha256=None, model_revision=None)

The planted decontamination test set: n_per items of each benchmark ?sec-lm-dedup

make_pred

make_pred(net, path, kind)

pred(x, alpha, sigma) -> (x0, eps) from net(x, t) of a kind on path. Abschnitt 17.3

make_step

make_step(model, forward=None, bf16=False, warmup=0)

An AdamW training step of model on a minibatch (X, Y); forward Abschnitt 13.8

map_qwen3_state_dict

map_qwen3_state_dict(hf_state, cfg, rope_layout='permute')

A Qwen3GPT state dict from a Transformers Qwen3 state dict. Renames ?sec-lm-d2l-checkpoint

masked_softmax

masked_softmax(X, mask=None)

Softmax over the last axis with zero weight where mask is False. Abschnitt 10.2

min_detectable_effect

min_detectable_effect(sd=None, n=None, se=None, deff=1.0, alpha=0.05, power=0.8)

Smallest true difference that a two-sided level-alpha test detects ?sec-lm-eval-suites

minhash_signature

minhash_signature(shingle_list, k=128, seed=210)

The MinHash signature, a (k,) uint64 array, of a shingle collection: ?sec-lm-dedup

mix_pools

mix_pools(c, root=os.path.join('..', 'data', 'lm', 'mix'))

(pools, val), each {domain: TokenPool}, of a MIX_CONFIGS entry c: ?sec-lm-data-mixtures

mix_run_specs

mix_run_specs(c)

The run design of a MIX_CONFIGS entry c, in launch order: the ?sec-lm-data-mixtures

mixture_logpdf

mixture_logpdf(x, mus, As)

Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k). Abschnitt 16.2

mixup

mixup(X, y, alpha)

Mix a minibatch with a shuffled copy; return both label sets. Abschnitt 7.6

mlm_corrupt

mlm_corrupt(ids, mask_id, vocab_size, special_ids, p=0.15, probs=(0.8, 0.1, 0.1), generator=None)

BERT’s masked-token corruption of ids: each token that is not in ?sec-lm-bert

mmd2_unbiased

mmd2_unbiased(K_pp, K_qq, K_pq)

Unbiased MMD^2 from the kernel matrices within p, within q, and Abschnitt 16.2

multibox_detection

multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5, pos_threshold=0.009999999)

Predict bounding boxes using non-maximum suppression. ?sec-anchor

multibox_prior

multibox_prior(data, sizes, ratios)

Generate anchor boxes with different shapes centered on each pixel. ?sec-anchor

multibox_target

multibox_target(anchors, labels)

Label anchor boxes using ground-truth bounding boxes. ?sec-anchor

naive_blocks

naive_blocks(page)

The text blocks of a page, split at block-level tags, as (text, ?sec-lm-crawl

near_dedup

near_dedup(texts, threshold=0.8, ngram=5, num_perm=128, seed=0, workers=1)

The indices of texts to keep after near-duplicate removal: MinHash ?sec-lm-dedup

nearest_neighbors

nearest_neighbors(E, vocab, word, k=5, exclude_self=True)

The k rows of E nearest to word’s row in cosine, as a list of ?sec-lm-word-embeddings

nms

nms(boxes, scores, iou_threshold)

Sort confidence scores of predicted bounding boxes. ?sec-anchor

no_duplicate_batches

no_duplicate_batches(queries, passages, batch_size, seed=0, negatives=None)

Batches of indices into the pairs (queries[i], passages[i]), in a ?sec-lm-text-embeddings

noise_scale

noise_scale(model, sample, b_small=16, b_big=2048, m=400)

Gradient-noise scale from the mean squared gradient norms of m Abschnitt 9.8

normalize_url

normalize_url(url)

A URL in the form the validation split deduplicates on: scheme and ?sec-lm-tokenizers

num_gpus

num_gpus()

Get the number of available GPUs. Abschnitt 5.7

num_params

num_params(model)

The number of trainable parameters. Abschnitt 7.5.1.1

ode_sample

ode_sample(pred, x, sigma_bars)

Euler (= DDIM) on d x_bar / d sigma_bar = eps, from x to data; x is the Abschnitt 17.3

offset_boxes

offset_boxes(anchors, assigned_bb, eps=1e-06)

Transform for anchor box offsets. ?sec-anchor

offset_inverse

offset_inverse(anchors, offset_preds)

Predict bounding boxes based on anchor boxes with predicted offsets. ?sec-anchor

on_grid

on_grid(runs, grid, col, smooth=1)

Resample per-episode rows (env step, value, …) onto an env-step Abschnitt 39.9

openrouter_api

openrouter_api(model, provider, listing, cache=None, mode='replay', cost_cap_usd=None, reasoning=None, when=None, **kwargs)

A d2l.ChatAPI for one model on OpenRouter with one provider pinned ?sec-lm-api

padding_mask

padding_mask(valid_lens, num_keys)

Boolean mask that is True for the first valid_lens keys. Abschnitt 10.2

pair_stats

pair_stats(net_D, real, fake, y=None)

Ranking accuracy P(D(x) > D(x’)) and mean rank weight Abschnitt 16.5

pair_texts

pair_texts(row, texts, vocab=None)

The two texts of a labelled pair: texts[a] and texts[b], or texts[a] ?sec-lm-dedup

paired_bootstrap

paired_bootstrap(scores_a, scores_b, n_boot=10000, cluster=None, seed=0, alpha=0.05)

bootstrap_ci of the per-item differences scores_a - scores_b on the ?sec-lm-eval-suites

pass_at_k

pass_at_k(n, c, k)

Unbiased pass@k from n samples of which c are correct: the ?sec-lm-scoring

pass_at_k_variance

pass_at_k_variance(n, p, k)

Variance of pass_at_k(n, c, k) when c ~ Binomial(n, p): the sum over ?sec-lm-scoring

peak_memory

peak_memory(f, *args)

Extra peak GPU memory allocated by f(*args), in bytes. Abschnitt 5.7

percentile_ci

percentile_ci(values, alpha=0.05, names=None)

Percentile endpoints of bootstrap replicates (along axis 0), over ?sec-lm-interpretability

plain_sgd

plain_sgd(net, lr)

A plain SGD optimizer over the parameters of net. Abschnitt 39.9

plain_surrogate

plain_surrogate(rho, adv, epsilon)

The unclipped per-sample objective rho A. Abschnitt 15.2

plot

plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None, legend_loc=None)

Plot data points. Abschnitt 39.9

plot_curves

plot_curves(curves, xlabel, ylabel, smooth=1, reference=None, ylim=None, x=None, xscale='linear', yscale='linear', band='range')

One panel per call. curves maps a label to an array of shape Abschnitt 39.9

plot_hist

plot_hist(samples, xlabel, ylabel, bins=60, vlines=())

Overlaid histograms of samples (label -> values), dashed at vlines. Abschnitt 39.9

plot_intervals

plot_intervals(x, series, xlabel, ylabel, kind='errorbar', reference=None, xscale='linear', axes=None, marks=None)

Estimates with intervals: series maps a label to (mean, lo, hi); Abschnitt 39.9

policy_evaluation

policy_evaluation(mdp, pi, num_iters)

Same sweep with the max replaced by an average under pi(a|s). Abschnitt 14.2

policy_objective

policy_objective(theta, P, r, gamma)

J(theta) = V(s0) of the softmax policy, a differentiable linear solve. Abschnitt 14.7

policy_step

policy_step(ac, obs, act, weight)

One ascent step on (1/n) sum_t w_t log pi(a_t|s_t) over a batch of Abschnitt 14.5

pool_hidden

pool_hidden(hidden, attention_mask, mode)

One vector per sequence from hidden states (B, T, m): the first ?sec-lm-text-embeddings

ppmi

ppmi(counts, alpha=1.0, shift=0.0)

Positive (shifted) PMI of a count matrix as a scipy.sparse.csr_matrix: ?sec-lm-word-embeddings

ppo_epochs

ppo_epochs(ac, obs, act, adv, logp_old, epsilon, num_epochs, entropy_coef=0.01, surrogate=clipped_surrogate)

num_epochs passes on the mean surrogate plus an entropy bonus, on one Abschnitt 15.2

precision_recall

precision_recall(feat_real, feat_gen, k=3, chunk=1000)

k-NN precision and recall of two feature sets: the fraction of each Abschnitt 16.5

pred_bar

pred_bar(pred, xb, r)

pred at x = alpha x_bar, sigma_bar = r; at r = inf, x_bar is noise. Abschnitt 17.3

predict_seq2seq

predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps, device, save_attention_weights=False)

Predict for sequence to sequence. Abschnitt 39.9

preprocess_nmt

preprocess_nmt(text)

Preprocess the English-French dataset. Abschnitt 39.9

price_from_listing

price_from_listing(listing, model_id, provider, when=None)

The d2l.PricePoint (USD per million tokens) of one provider’s endpoint ?sec-lm-api

probe_endpoint

probe_endpoint(name, api, base, on, off, max_tokens, model_id, story, count, rules, temperature)

Rows (endpoint, field, status, evidence, UTC date) of the field ?sec-lm-api

proxy_flops

proxy_flops(cfg, tokens, n_params)

Training FLOP of a proxy run: 6 N D for the parameters plus ?sec-lm-data-mixtures

q_learning

q_learning(seed, Q, visits, env, num_episodes, gamma, alpha=lambda n: 1 / (1 + 0.1 * n), epsilon=None)

Tabular Q-learning; updates Q in place, yields each episode’s return. Abschnitt 14.3

quadratic_kappa

quadratic_kappa(a, b, k=6)

Quadratic-weighted kappa of two integer scores in 0..k-1: one minus ?sec-lm-quality-filtering

query_accuracy

query_accuracy(model, X, Y)

Fraction of queries answered correctly. Abschnitt 12.1.4

qwen3_gpt_kwargs

qwen3_gpt_kwargs(cfg)

Qwen3GPT’s arguments from a Qwen3 configuration (a dict or a ?sec-lm-d2l-checkpoint

qwen3_rope_permutation

qwen3_rope_permutation(head_dim)

Index idx with idx[2i] = i and idx[2i + 1] = i + head_dim / 2: taking ?sec-lm-d2l-checkpoint

qwen3_rope_tables

qwen3_rope_tables(n, head_dim, theta, offset=0, device=None)

Cosines and sines, each (n, head_dim / 2) in fp32, of the RoPE angles ?sec-lm-d2l-checkpoint

r1_r2_penalty

r1_r2_penalty(critic, real, fake)

Per-sample squared critic input gradients on real (R1) and fake (R2), Abschnitt 16.4

r2_tokenizer

r2_tokenizer(raw=False)

The reference tokenizer (artifact lm-r2-tokenizer-v1; its file is ?sec-lm-tokenizers

rag_judge

rag_judge(judge, tokenizer, item, result, context_texts, batch_size=8, thinking=None, max_new_tokens=None)

The judge’s verdicts on an answer: ‘correct’ (every key fact stated, ?sec-lm-rag

rag_judge_servers

rag_judge_servers(gpus=None, vllm=None)

One d2l.LocalChatServer per GPU (default: every visible GPU), each ?sec-lm-rag

rag_prompt

rag_prompt(question, hits, abstain=ABSTAIN)

Chat messages asking for an answer from numbered passages (hits: Hit ?sec-lm-rag

rank_auc

rank_auc(y, s)

ROC AUC of scores s for boolean labels y (Mann-Whitney, ties at ?sec-lm-quality-filtering

read_conllu

read_conllu(path, stride, max_words)

Every stride-th sentence of a CoNLL-U file, up to max_words words: ?sec-lm-interpretability

read_csv_labels

read_csv_labels(fname)

Read fname to return a filename to label dictionary. ?sec-kaggle-cifar10

read_data_bananas

read_data_bananas(is_train=True)

Read the banana detection dataset images and labels. ?sec-object-detection-dataset

read_data_nmt

read_data_nmt()

Load the English-French dataset. Abschnitt 39.9

read_docs

read_docs(path)

The documents of a file written by write_docs, as a list of Doc ?sec-lm-crawl

read_jsonl

read_jsonl(path)

A file of JSON lines as a DataFrame, one row per line, values with ?sec-lm-scoring

read_voc_images

read_voc_images(voc_dir, is_train=True)

Read all VOC feature and label images. ?sec-semantic-segmentation

rebuild_c0

rebuild_c0(manifest='lm-c0-docs-v1', warc_path=None, cache_dir=None, workers=None)

Rebuild the c0 documents from their manifest rows (a DATA_HUB key or ?sec-lm-crawl

record_field_probe

record_field_probe(path, endpoints, local_name, listing, providers, **kwargs)

Probe every endpoint at once (name -> (client, base, on, off, ?sec-lm-api

registered_domain

registered_domain(url)

The registered domain of a URL (example.co.uk for ?sec-lm-crawl

regression_loss

regression_loss(path, kind)

Squared error of net(x_t, t) against the target of a kind, t ~ U(0, 1). Abschnitt 17.2

released_edu_scores

released_edu_scores(texts, batch=64, device=None, dtype=None)

Scores of the released FineWeb-Edu classifier (a regression head on ?sec-lm-quality-filtering

reorg_test

reorg_test(data_dir)

Organize the testing set for data loading during prediction. ?sec-kaggle-cifar10

reorg_train_valid

reorg_train_valid(data_dir, labels, valid_ratio)

Split the validation set out of the original training set. ?sec-kaggle-cifar10

repeated_spans

repeated_spans(ids, sa, lcp, min_len)

The maximal repeats of at least min_len tokens, as (start, length, ?sec-lm-dedup

rephrase_docs

rephrase_docs(chunks, style, model_id='Qwen/Qwen3.5-2B', max_new_tokens=512, batch=32, temperature=0.7, top_p=0.9, seed=0, backend='hf', model=None, progress=None)

Rewrite each text of chunks in a style: a key of REPHRASE_PROMPTS, ?sec-lm-synthetic-data

request_hash

request_hash(base_url, model, messages, params, replica=0)

sha256 of the canonical JSON (sorted keys, no whitespace, UTF-8) of ?sec-lm-api

rerank_yes_no

rerank_yes_no(model, tokenizer, query, docs, instruction=None, batch_size=16, max_len=1024)

P(yes) of a yes/no reranker (Qwen3-Reranker) that each document ?sec-lm-retrieval

resnet18

resnet18(num_classes, in_channels=1)

ResNet-18 for small images: a 3x3 stem without max-pooling, He Abschnitt 13.6

retrieval_metrics

retrieval_metrics(ranked_ids, gold_ids, ks=(1, 5, 10, 100))

Per-query metrics of ranked lists against gold sets (binary ?sec-lm-text-embeddings

rollout

rollout(env, policy, num_episodes, rng)

Collect complete episodes from policy(obs, rng) -> action as a Abschnitt 14.7

rope

rope(x, offset=0, base=10000.0, scale=None, tables=None)

Rotate feature pairs of x (…, num_steps, d) by position angles; Abschnitt 10.4

rope_tables

rope_tables(n, d, offset=0, base=10000.0, scale=None, device=None)

Cosines and sines, each (n, d/2), of the angles of the positions Abschnitt 10.4

rpgan_loss_D

rpgan_loss_D(critic, real, fake)

Relativistic pairing critic loss -E[log sigma(D(x) - D(x’))]. Abschnitt 16.3

rpgan_loss_G

rpgan_loss_G(critic, real, fake)

Non-saturating pairing loss for the generator. Abschnitt 16.3

rrf_fuse

rrf_fuse(rankings, k=60, weights=None)

Reciprocal-rank fusion: each id scores sum_r w_r / (k + rank_r) over ?sec-lm-retrieval

run_python_tests

run_python_tests(program, test_code, timeout=5.0)

True iff program followed by test_code runs to its end and the ?sec-lm-scoring

run_seeds

run_seeds(train, num_seeds, **kwargs)

Run train(seed, **kwargs), a generator of curve points, per seed. Abschnitt 39.9

sae_acts

sae_acts(sae, H, feats, chunk=2048)

The activations of the features feats of sae on H (docs, positions, ?sec-lm-interpretability

sae_fire_rate

sae_fire_rate(sae, H, chunk=2048)

The fraction of the positions of H (…, d) where each feature of ?sec-lm-interpretability

sae_metrics

sae_metrics(sae, model, token_batches, layer)

L0, FVU, loss recovered and firing density of sae on the stream ?sec-lm-interpretability

safetensors_header

safetensors_header(model_id, revision=None, timeout=30)

Shape and dtype of every tensor of a Hub checkpoint, read by HTTP ?sec-lm-hf-models

sample_logits

sample_logits(logits, strategy='greedy', temperature=1.0, k=None, p=None, min_p=None, generator=None)

One token id per row of logits (batch, vocab): the argmax (ties to ?sec-lm-d2l-checkpoint

sample_mixture

sample_mixture(n, mus, As, rng)

n draws from the uniform mixture of Gaussians mu_k + z A_k. Abschnitt 16.2

sample_mixtures

sample_mixtures(n, domains, concentration, seed, max_weight=0.9, min_weight=0.0)

n mixtures over the domains, (n, m), drawn from the symmetric ?sec-lm-data-mixtures

sample_real

sample_real(images, n, labels=None)

Draw a training batch with random horizontal flips; return it with Abschnitt 16.5

save_checkpoint

save_checkpoint(path, model, optimizer, step, cfg=None, rng=None)

Atomically write a resumable training checkpoint. Abschnitt 5.6

scatter_panels

scatter_panels(samples, titles=None, data=None, lim=4.5, size=3.0)

Scatter 2-D point sets side by side on equal, shared axes. Abschnitt 17.1

score_choices

score_choices(model, tokenizer, prompts, choices, norm='token', batch_size=8, return_components=False)

Log-likelihood scores (N, C_max) of each choice after its prompt, ?sec-lm-scoring

scrub_pii

scrub_pii(text)

Replace email addresses by <EMAIL> and public IPv4 and IPv6 ?sec-lm-crawl

scurve

scurve(s, b, r)

The probability that a pair of Jaccard s becomes a candidate under b ?sec-lm-dedup

sequence_mask

sequence_mask(X, valid_len, value=0)

Mask irrelevant entries in sequences. Abschnitt 39.9

set_axes

set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend, legend_loc=None)

Set the axes for matplotlib. legend_loc is a matplotlib legend Abschnitt 39.9

set_figsize

set_figsize(figsize=(3.5, 2.5))

Set the figure size for matplotlib. Abschnitt 39.9

set_log_ticks

set_log_ticks(axis)

Label all major ticks of a log axis in one format. Abschnitt 39.9

sgd

sgd(params, lr, batch_size)

Minibatch stochastic gradient descent. Abschnitt 39.9

sgns_loss

sgns_loss(v, u, centers, contexts_negatives, labels, masks)

Skip-gram with negative sampling: the binary cross-entropy of the ?sec-lm-word-embeddings

shingles

shingles(text, n=5)

The word n-grams of text as strings (the MinHash specification): ?sec-lm-dedup

show_bboxes

show_bboxes(axes, bboxes, labels=None, colors=None)

Show bounding boxes. ?sec-anchor

show_gray

show_gray(imgs, num_rows, num_cols, titles=None, scale=1.0)

Show images (n, 1, h, w) in [-1, 1], or binary (n, h, w), in gray. Abschnitt 17.1

show_grid

show_grid(desc, values, policy=None, titles=None, diverging=False, fmt='{:.2f}')

A gridworld in the style of the chapter’s figures. Each cell is Abschnitt 39.9

show_heatmaps

show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5), cmap='Reds', cbar=True, xticklabels=None, yticklabels=None)

Show heatmaps of matrices; cbar is True (shared), ‘each’ or False. Abschnitt 39.9

show_images

show_images(imgs, num_rows, num_cols, titles=None, scale=1.5, cmap=None, vmin=None, vmax=None)

Plot a list of images (cmap colors single-channel images, on the Abschnitt 39.9

show_kernels

show_kernels(kernels, rows=4)

The kernels of a decode step with the most device time: ms and share ?sec-lm-hf-models

show_profile

show_profile(kernels, step_ms, rows=6)

Busy device time against the wall-clock time step_ms of a step, the Abschnitt 13.1

show_trace_2d

show_trace_2d(f, results)

Show the trace of 2D variables over the contours of f. Abschnitt 39.9

sinusoidal_encoding

sinusoidal_encoding(max_len, num_hiddens)

The (max_len, num_hiddens) table of sinusoidal position codes. Abschnitt 10.4

smooth

smooth(losses, k=25)

Means over consecutive blocks of k losses, for plotting. Abschnitt 9.5

sp_train

sp_train(texts, model_type, vocab_size, **kw)

A SentencePiece model trained on texts (one input line per line of ?sec-lm-tokenizers

span_f1

span_f1(pred_tags, gold_tags, id2label)

Entity-level precision, recall and F1 of IOB2 tag sequences (a list ?sec-lm-bert

spearman_eval

spearman_eval(embeddings, vocab, pairs, n_boot=2000, seed=0)

Spearman correlation between the cosine similarities of embeddings ?sec-lm-word-embeddings

squared_loss

squared_loss(y_hat, y)

Squared loss. Abschnitt 39.9

standardize

standardize(x, eps=1e-08)

Center a NumPy batch of weights and divide by its standard deviation Abschnitt 14.8

steps_to

steps_to(run, level, window)

Env steps at which the mean return of the last window rows of Abschnitt 15.1

steps_to_reach

steps_to_reach(losses, target, k=25)

First step at which the smoothed losses reach target; None if they Abschnitt 9.5

structure_recall

structure_recall(html, text)

Recall of a page’s structural content in an extracted text: the ?sec-lm-crawl

subset_ids

subset_ids(n_total, n, seed=0)

Row indices of a seeded subset of n of n_total items: the first n ?sec-lm-eval-suites

suffix_array

suffix_array(ids)

The suffix array of an integer sequence by prefix doubling: sa[i] is ?sec-lm-dedup

synth_metrics

synth_metrics(src, out)

Fidelity of a rewrite out of src: copy_rate, the Jaccard similarity ?sec-lm-synthetic-data

synthetic_data

synthetic_data(w, b, noise, n)

n examples with standard normal features and labels Xw + b + noise. Abschnitt 2.2

tabular_score

tabular_score(obs, act, w, pi)

sum_t w_t (e_{a_t} - pi(.|s_t)), each term added into row s_t: the Abschnitt 14.7

tanh_mlp

tanh_mlp(in_dim, hidden, out_dim)

A network with one tanh hidden layer. Abschnitt 14.9

temperature_weights

temperature_weights(sizes, alpha)

Sampling probabilities p_i proportional to n_i ** alpha: alpha = 1 ?sec-lm-data-mixtures

text_table

text_table(make_model, arms, data, num_runs=2, num_steps=1000)

Train num_runs fresh models make_model(*args) for each arm (a name Abschnitt 12.1.4

tile_images

tile_images(imgs, num_rows)

Tile images (n, 3, h, w) in [-1, 1] into one (rows * h, cols * w, 3) Abschnitt 16.5

time_embedding

time_embedding(t, dim, freqs=(1.0, 64.0))

Sines and cosines of t at dim / 2 frequencies, geometric from freqs[0] Abschnitt 17.1

token_byte_lengths

token_byte_lengths(tokenizer)

np.ndarray of the UTF-8 bytes each token id stands for (0 for ?sec-lm-data-mixtures

tokenize

tokenize(lines, token='word')

Split text lines into word or character tokens. Abschnitt 39.9

tokenize_nmt

tokenize_nmt(text, num_examples=None)

Tokenize the English-French dataset. Abschnitt 39.9

torchrun

torchrun(script, nproc, *args, env=None)

Run Python source in nproc processes; return their JSON lines. Abschnitt 13.6

train_2d

train_2d(trainer, f_grad, steps=20, **hparams)

Run a 2D update rule from (-5, -2) and return the iterates. Abschnitt 9.1

train_batch_ch13

train_batch_ch13(net, X, y, loss, trainer, devices)

Train for a minibatch with multiple GPUs (defined in Chapter 13). ?sec-image-augmentation

train_ch13

train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices=d2l.try_all_gpus())

Train a model with multiple GPUs (defined in Chapter 13). ?sec-image-augmentation

train_ch6

train_ch6(net, train_iter, test_iter, num_epochs, lr, device)

Train a model with a GPU (defined in Chapter 6). Abschnitt 39.9

train_delayed_recall

train_delayed_recall(model, num_steps, blank_fillers=False)

Train with Adam at rate 0.003 on 1,500 fresh batches of 128 sequences Abschnitt 12.1.4

train_feature_cnn

train_feature_cnn(cnn, X, y, num_epochs=15, max_lr=0.003, batch_size=256, shift=0, seed=0)

Train on random horizontal flips, plus random shifts of up to shift Abschnitt 39.9

train_gan

train_gan(net_D, net_G, data_iter, num_epochs, latent_dim, lr_D, lr_G, step_G=update_G, seed=None, on_epoch=None, ema=None)

Alternate update_D and step_G over the minibatches with Adam Abschnitt 16.1

train_hf_bpe

train_hf_bpe(texts, vocab_size, specials, regex=R2_SPLIT_REGEX, min_frequency=2)

A byte-level BPE (Hugging Face tokenizers) trained on texts: NFC, ?sec-lm-tokenizers

train_queries

train_queries(model, batch, num_steps, optimizer, scheduler=None)

Train on fresh batches; the queries are the last Y.shape[1] steps. Abschnitt 12.1.4

train_r3gan

train_r3gan(net_G, net_D, loss_D, loss_G, gamma, num_steps, images, labels=None, eval_images=None, eval_labels=None, eval_size=256, batch_size=64, lr=0.0002, half_life=500, log_every=250, seed=None)

Train with Adam (beta_1 = 0), alternating critic_step and Abschnitt 16.5

train_recall

train_recall(model, pairs=(4, 8, 16, 32, 64), num_updates=2000, **task)

Train on associative recall (task: options of associative_recall) Abschnitt 12.6

train_regression

train_regression(model, loss_fn, batch_fn, num_steps, lr=0.001, cosine=False, ema_half_life=1000, compiled=True)

Adam on loss_fn(model, batch_fn()) -> (model, EMA model, losses). Abschnitt 17.1

train_reinforce_tabular

train_reinforce_tabular(ac, env, gamma, seed, num_updates=256, batch_episodes=16)

REINFORCE: a fresh batch from the current policy, every step of a Abschnitt 14.7

train_sae

train_sae(sae, activations, steps, batch_size=4096, lr=0.0002, aux_coef=1 / 32, dead_after=200, seed=0)

Train a TopKSAE with Adam on random rows of activations (N, d), with ?sec-lm-interpretability

train_seq2seq

train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device)

Train a model for sequence to sequence. Abschnitt 39.9

train_shift

train_shift(critic_loss, gen_loss, seed, gp=0.0, one_sided=False, theta0=6.0, steps=1500, n_critic=5, batch=256, lr_D=0.01, lr_G=0.01)

Fit x’ = theta + z to N(0, 1) by plain gradient steps on theta; return Abschnitt 16.2

train_step_gflops

train_step_gflops(net, loss_fn, shape, batch_size=128)

GFLOP of one training step, forward and backward, on a batch of zeros Abschnitt 17.7

train_steps

train_steps(model, data, optimizer, num_steps, stop=None)

Minimize the mean cross-entropy of the logits model(X) for the labels Abschnitt 9.5

train_text

train_text(model, data, lr=0.002, num_steps=1000)

Train a language model with LMOptimizer; return its validation loss Abschnitt 12.1.4

train_toy

train_toy(critic_loss, gen_loss, seed=0, steps=6000, batch=256, lr=0.001)

Fit a MixtureGenerator from (mu_0, A_0) to the data mixture, one Abschnitt 16.2

truncate_embeddings

truncate_embeddings(Z, dim)

The first dim coordinates of each row of Z, rescaled to unit length. ?sec-lm-text-embeddings

truncate_pad

truncate_pad(line, num_steps, padding_token)

Truncate or pad sequences. Abschnitt 39.9

truncated_probs

truncated_probs(logits, temperature=1.0, k=None, p=None, min_p=None)

Rows of logits (batch, vocab) -> the temperature-scaled distribution ?sec-lm-d2l-checkpoint

try_all_gpus

try_all_gpus()

Return all available GPUs, or [cpu(),] if no GPU exists. Abschnitt 5.7

try_gpu

try_gpu(i=0)

Return gpu(i) if exists, otherwise return cpu(). Abschnitt 5.7

type_tag_baseline

type_tag_baseline(train_types, train_tags, test_types)

Per test word, the most frequent training tag of its word type, or ?sec-lm-interpretability

union_find_clusters

union_find_clusters(n, pairs)

Connected components of n items under pairs, by union-find (path ?sec-lm-dedup

update_D

update_D(X, Z, net_D, net_G, trainer_D)

Update the critic; return its log loss summed over both batches Abschnitt 16.1

update_G

update_G(Z, net_D, net_G, trainer_G)

Update the generator on the non-saturating loss; return its sum. Abschnitt 16.1

use_svg_display

use_svg_display()

Use the svg format to display a plot in Jupyter. Abschnitt 39.9

valley_grad

valley_grad(x1, x2)

Gradient of f_valley. Abschnitt 9.1

value_iteration

value_iteration(mdp, num_iters)

Sweep V <- max_a backup(V); return the whole history of iterates. Abschnitt 14.2

verifier_step

verifier_step(task, theta, K, reward, rng, weighting, lr=2.0)

One REINFORCE step on a VerifierTask: K responses per prompt, each Abschnitt 14.7

viterbi_segment

viterbi_segment(text, logp, max_len, unk=None)

The most probable segmentation of text into pieces of logp (piece ?sec-lm-tokenizers

voc_colormap2label

voc_colormap2label()

Build the mapping from RGB to class indices for VOC labels. ?sec-semantic-segmentation

voc_label_indices

voc_label_indices(colormap, colormap2label)

Map any RGB values in VOC labels to their class indices. ?sec-semantic-segmentation

voc_rand_crop

voc_rand_crop(feature, label, height, width)

Randomly crop both feature and label images. ?sec-semantic-segmentation

warc_record_at

warc_record_at(path, offset, length)

The WarcRecord stored in bytes offset..offset+length-1 of a local ?sec-lm-crawl

wilson_ci

wilson_ci(k, n, z=1.96)

Wilson score interval for a binomial proportion k / n. ?sec-lm-quality-filtering

windows

windows(corpus, batch_size, num_steps=128)

Endless minibatches of windows at random offsets, each position with Abschnitt 13.8

word_windows

word_windows(text, size=128, stride=64)

Windows of size whitespace-separated words every stride words, the ?sec-lm-dedup

write_api_manifests

write_api_manifests(clients, record_dir)

Append this session to the manifest.json of every cache folder under ?sec-lm-api

write_docs

write_docs(path, docs)

Write documents (Doc or dicts with Doc’s fields) as gzip-compressed ?sec-lm-crawl

write_jsonl

write_jsonl(path, records)

Write records (dicts) as JSON lines. ?sec-lm-scoring

write_shards

write_shards(docs, tokenizer, out_dir, split, shard_tokens=100000000, eos_id=None, meta_fn=None, manifest=None, batch_docs=1000, max_shards=None)

Tokenize documents into shards out_dir/{split}-{k:05d}.bin|.idx| ?sec-lm-tokenizers

accuracy

accuracy(y_hat, y)

Compute the number of correct predictions. Abschnitt 39.9

add_to_class

add_to_class(Class)

Register functions as methods in created class. Abschnitt 2.4

as_metrics

as_metrics(out)

A step returns a loss or a dict of metrics; return a dict. Abschnitt 2.4

assign_anchor_to_bbox

assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5)

Assign closest ground-truth bounding boxes to anchor boxes. ?sec-anchor

bbox_to_rect

bbox_to_rect(bbox, color)

Convert bounding box to matplotlib format. ?sec-bbox

beam_search

beam_search(step_fn, prefix, num_tokens, beam_size=4, alpha=0.75, eos_id=None)

Length-normalized beam search (score = log P / len^alpha). Abschnitt 8.6.3

box_center_to_corner

box_center_to_corner(boxes)

Convert from (center, width, height) to (upper-left, lower-right). ?sec-bbox

box_corner_to_center

box_corner_to_center(boxes)

Convert from (upper-left, lower-right) to (center, width, height). ?sec-bbox

box_iou

box_iou(boxes1, boxes2)

Compute pairwise IoU across two lists of anchor or bounding boxes. ?sec-anchor

build_array_nmt

build_array_nmt(lines, vocab, num_steps)

Transform text sequences of machine translation into minibatches. Abschnitt 39.9

check_shape

check_shape(a, shape)

Check the shape of a tensor. Abschnitt 8.4.2

copyfile

copyfile(filename, target_dir)

Copy a file into a target directory. ?sec-kaggle-cifar10

corr2d

corr2d(X, K)

Compute 2D cross-correlation. Abschnitt 6.2

corrupt

corrupt(y, fraction, rng)

Replace each label, with probability fraction, by a random class. Abschnitt 4.5

cosine_warmup

cosine_warmup(t, num_steps, warmup_steps)

Learning-rate factor: linear warmup from 0, then a half-cosine to 0. Abschnitt 7.1

cpu

cpu()

Get the CPU device. Abschnitt 5.7

download

download(url, folder='../data', sha1_hash=None)

Download a file to folder and return the local filepath. Abschnitt 39.9

download_extract

download_extract(name, folder=None)

Download and extract a zip/tar file. Abschnitt 39.9

drop_path

drop_path(Y, p, training)

Zero each example of Y with probability p, rescale the rest. Abschnitt 7.6

evaluate_accuracy

evaluate_accuracy(net, data_iter)

Compute the accuracy for a model on a dataset. Abschnitt 39.9

evaluate_loss

evaluate_loss(net, data_iter, loss)

Evaluate the loss of a model on the given dataset. Abschnitt 39.9

extract

extract(filename, folder=None)

Extract a zip/tar file into folder. Abschnitt 39.9

get_fashion_mnist_labels

get_fashion_mnist_labels(labels)

Return text labels for the Fashion-MNIST dataset. Abschnitt 39.9

gpu

gpu(i=0)

Get a GPU device. Abschnitt 5.7

grad_clipping

grad_clipping(grads, theta)

Clip the gradient. Abschnitt 39.9

kneser_ney

kneser_ney(train, tokens, vocab_size, n=3)

Interpolated Kneser-Ney log-probabilities (nats) of each of tokens. Abschnitt 8.3

linreg

linreg(X, w, b)

The linear regression model. Abschnitt 39.9

load_array

load_array(data_arrays, batch_size, is_train=True)

Construct a TensorFlow data iterator. Abschnitt 39.9

load_data_bananas

load_data_bananas(batch_size)

Load the banana detection dataset. ?sec-object-detection-dataset

load_data_fashion_mnist

load_data_fashion_mnist(batch_size, resize=None)

Download the Fashion-MNIST dataset and then load it into memory. Abschnitt 39.9

load_data_nmt

load_data_nmt(batch_size, num_steps, num_examples=600)

Return the iterator and the vocabularies of the translation dataset. Abschnitt 39.9

load_data_voc

load_data_voc(batch_size, crop_size)

Load the VOC semantic segmentation dataset. ?sec-semantic-segmentation

mixup

mixup(X, y, alpha)

Mix a minibatch with a shuffled copy; return both label sets. Abschnitt 7.6

multibox_detection

multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5, pos_threshold=0.009999999)

Predict bounding boxes using non-maximum suppression. ?sec-anchor

multibox_prior

multibox_prior(data, sizes, ratios)

Generate anchor boxes with different shapes centered on each pixel. ?sec-anchor

multibox_target

multibox_target(anchors, labels)

Label anchor boxes using ground-truth bounding boxes. ?sec-anchor

nms

nms(boxes, scores, iou_threshold)

Sort confidence scores of predicted bounding boxes. ?sec-anchor

num_gpus

num_gpus()

Get the number of available GPUs. Abschnitt 5.7

num_params

num_params(model)

The number of trainable parameters. Abschnitt 7.5.1.1

offset_boxes

offset_boxes(anchors, assigned_bb, eps=1e-06)

Transform for anchor box offsets. ?sec-anchor

offset_inverse

offset_inverse(anchors, offset_preds)

Predict bounding boxes based on anchor boxes with predicted offsets. ?sec-anchor

plot

plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None, legend_loc=None)

Plot data points. Abschnitt 39.9

predict_seq2seq

predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps, save_attention_weights=False)

Predict for sequence to sequence. Abschnitt 39.9

preprocess_nmt

preprocess_nmt(text)

Preprocess the English-French dataset. Abschnitt 39.9

read_csv_labels

read_csv_labels(fname)

Read fname to return a filename to label dictionary. ?sec-kaggle-cifar10

read_data_bananas

read_data_bananas(is_train=True)

Read the banana detection dataset images and labels. ?sec-object-detection-dataset

read_data_nmt

read_data_nmt()

Load the English-French dataset. Abschnitt 39.9

read_voc_images

read_voc_images(voc_dir, is_train=True)

Read all VOC feature and label images. ?sec-semantic-segmentation

reorg_test

reorg_test(data_dir)

Organize the testing set for data loading during prediction. ?sec-kaggle-cifar10

reorg_train_valid

reorg_train_valid(data_dir, labels, valid_ratio)

Split the validation set out of the original training set. ?sec-kaggle-cifar10

resnet18

resnet18(num_classes, in_channels=1)

A slightly modified ResNet-18 model built with Keras. Abschnitt 13.6

sequence_mask

sequence_mask(X, valid_len, value=0)

Mask irrelevant entries in sequences. Abschnitt 39.9

set_axes

set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend, legend_loc=None)

Set the axes for matplotlib. legend_loc is a matplotlib legend Abschnitt 39.9

set_figsize

set_figsize(figsize=(3.5, 2.5))

Set the figure size for matplotlib. Abschnitt 39.9

set_log_ticks

set_log_ticks(axis)

Label all major ticks of a log axis in one format. Abschnitt 39.9

sgd

sgd(params, grads, lr, batch_size)

Minibatch stochastic gradient descent. Abschnitt 39.9

show_bboxes

show_bboxes(axes, bboxes, labels=None, colors=None)

Show bounding boxes. ?sec-anchor

show_heatmaps

show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5), cmap='Reds', cbar=True, xticklabels=None, yticklabels=None)

Show heatmaps of matrices; cbar is True (shared), ‘each’ or False. Abschnitt 39.9

show_images

show_images(imgs, num_rows, num_cols, titles=None, scale=1.5, cmap=None, vmin=None, vmax=None)

Plot a list of images (cmap colors single-channel images, on the Abschnitt 39.9

split_batch

split_batch(X, y, devices)

Split X and y into multiple devices. Abschnitt 13.5

squared_loss

squared_loss(y_hat, y)

Squared loss. Abschnitt 39.9

synthetic_data

synthetic_data(w, b, noise, n)

n examples with standard normal features and labels Xw + b + noise. Abschnitt 2.2

tokenize

tokenize(lines, token='word')

Split text lines into word or character tokens. Abschnitt 39.9

tokenize_nmt

tokenize_nmt(text, num_examples=None)

Tokenize the English-French dataset. Abschnitt 39.9

train_batch_ch13

train_batch_ch13(net, X, y, loss, optimizer)

Train for a minibatch with Keras (defined in Chapter 13). ?sec-image-augmentation

train_ch13

train_ch13(net, train_iter, test_iter, loss, optimizer, num_epochs)

Train a model with Keras (defined in Chapter 13). ?sec-image-augmentation

train_ch6

train_ch6(net_fn, train_iter, test_iter, num_epochs, lr, device)

Train a model with a GPU (defined in Chapter 6). Abschnitt 39.9

train_seq2seq

train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device)

Train a model for sequence to sequence. Abschnitt 39.9

truncate_pad

truncate_pad(line, num_steps, padding_token)

Truncate or pad sequences. Abschnitt 39.9

try_all_gpus

try_all_gpus()

Return all available GPUs, or [cpu(),] if no GPU exists. Abschnitt 5.7

try_gpu

try_gpu(i=0)

Return gpu(i) if exists, otherwise return cpu(). Abschnitt 5.7

use_svg_display

use_svg_display()

Use the svg format to display a plot in Jupyter. Abschnitt 39.9

voc_colormap2label

voc_colormap2label()

Build the mapping from RGB to class indices for VOC labels. ?sec-semantic-segmentation

voc_label_indices

voc_label_indices(colormap, colormap2label)

Map any RGB values in VOC labels to their class indices. ?sec-semantic-segmentation

voc_rand_crop

voc_rand_crop(feature, label, height, width)

Randomly crop both feature and label images. ?sec-semantic-segmentation

add_to_class

add_to_class(Class)

Register functions as methods in created class. Abschnitt 2.4

adjoint_scan

adjoint_scan(a, b)

All states of h_t = a_t * h_{t-1} + b_t, differentiated by a scan. Abschnitt 12.5

allreduce_megabytes

allreduce_megabytes(compiled)

Megabytes of fp32 results of each allreduce in a compiled program, Abschnitt 13.6

ancestral_sample

ancestral_sample(pred, x, path, steps, key, t_start=1.0)

Ho et al.’s sampler from x at t_start (1 is noise) to data at t = 0. Abschnitt 17.3

as_metrics

as_metrics(out)

A step returns a loss or a dict of metrics; return a dict. Abschnitt 2.4

assign_anchor_to_bbox

assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5)

Assign closest ground-truth bounding boxes to anchor boxes. ?sec-anchor

associative_recall

associative_recall(rng, batch_size, num_pairs, num_keys=512, num_values=4, num_steps=256, num_rebound=0, gap=None)

Key-value pairs, filler, then every key again as a query. The first Abschnitt 12.6

batch_to_heads

batch_to_heads(Y, batch_size)

(batch_size * num_heads, T, e) -> (batch_size, T, num_heads * e). Abschnitt 12.6

batched

batched(f, X, batch_size=1000)

Apply f to X in batches and concatenate. Abschnitt 16.5

bbox_to_rect

bbox_to_rect(bbox, color)

Convert bounding box to matplotlib format. ?sec-bbox

beam_search

beam_search(step_fn, prefix, num_tokens, beam_size=4, alpha=0.75, eos_id=None)

Length-normalized beam search (score = log P / len^alpha). Abschnitt 8.6.3

bleu

bleu(pred_seq, label_seq, k)

Compute the BLEU. Abschnitt 12.2.2

box_center_to_corner

box_center_to_corner(boxes)

Convert from (center, width, height) to (upper-left, lower-right). ?sec-bbox

box_corner_to_center

box_corner_to_center(boxes)

Convert from (upper-left, lower-right) to (center, width, height). ?sec-bbox

box_iou

box_iou(boxes1, boxes2)

Compute pairwise IoU across two lists of anchor or bounding boxes. ?sec-anchor

causal_mask

causal_mask(num_queries, num_keys=None)

Boolean (queries, keys) mask, True where a query may see a key. Abschnitt 10.2

ce_loss

ce_loss(model, X, Y)

Mean cross-entropy of the logits model(X) for the labels Y. Abschnitt 9.8

cfg

cfg(net, c, gamma)

Classifier-free guidance: (x, t) -> u + gamma (u_c - u), u unlabeled. Abschnitt 17.4

check_shape

check_shape(a, shape)

Check the shape of a tensor. Abschnitt 8.4.2

chrf

chrf(pred, label, n=6, beta=2)

chrF (Popovic, 2015): character n-gram F-score. Abschnitt 12.2.2

chunked_delta_rule

chunked_delta_rule(Q, K, V, beta, log_a, chunk_size)

Outputs y_t = S_t q_t of the gated delta rule, computed in chunks. Abschnitt 12.7

chunked_linear_attention

chunked_linear_attention(Q, K, V, log_a, chunk_size)

y_t = S_t q_t with S_t = a_t S_{t-1} + v_t k_t^T, computed in chunks. Abschnitt 12.6

clip_gradients

clip_gradients(grad_clip_val, grads)

Rescale the gradients to global norm at most grad_clip_val. Abschnitt 8.4.2

clipped_surrogate

clipped_surrogate(rho, adv, epsilon)

PPO’s per-sample objective eq_ppo_clip: min(rho A, clip(rho) A). Abschnitt 15.2

conditional

conditional(net, c)

The field (x, t) -> net(x, t, c) with the labels c fixed. Abschnitt 17.4

copyfile

copyfile(filename, target_dir)

Copy a file into a target directory. ?sec-kaggle-cifar10

corr2d

corr2d(X, K)

Compute 2D cross-correlation. Abschnitt 6.2

corrupt

corrupt(y, fraction, rng)

Replace each label, with probability fraction, by a random class. Abschnitt 4.5

cosine_warmup

cosine_warmup(t, num_steps, warmup_steps)

Learning-rate factor: linear warmup from 0, then a half-cosine to 0. Abschnitt 7.1

cpu

cpu()

Get the CPU device. Abschnitt 5.7

critic_step

critic_step(net_D, opt_D, loss_D, real, fake, gamma, y=None)

One critic step on loss_D + gamma/2 (R1 + R2); return the loss and Abschnitt 16.4

ddim_invert

ddim_invert(pred, x, path, steps, t_end=1.0)

Deterministic DDIM run backwards, from data x at t = 0 to t_end. Abschnitt 17.5

ddim_sample

ddim_sample(pred, x, path, steps, eta=0.0, key=None, t_start=1.0, t_end=0.0)

DDIM from x at t_start (1 is noise) to t_end; eta > 0 needs a key. Abschnitt 17.5

decay_mask

decay_mask(log_a)

L[t, s] = a_{s+1} * … * a_t for s <= t, and 0 for s > t. Abschnitt 12.6

delayed_recall

delayed_recall(rng, batch_size, num_steps, num_symbols=8, blank_fillers=False)

A symbol, then num_steps - 1 fillers; the target is the symbol. Abschnitt 12.1.4

delta_rule_writes

delta_rule_writes(K, V, beta, log_a)

W and Z with corrected values U = W - Z S_0^T, for every chunk. Abschnitt 12.7

download

download(url, folder='../data', sha1_hash=None)

Download a file to folder and return the local filepath. Abschnitt 39.9

download_extract

download_extract(name, folder=None)

Download and extract a zip/tar file. Abschnitt 39.9

drop_path

drop_path(key, Y, p, training)

Zero each example of Y with probability p, rescale the rest. Abschnitt 7.6

edm_grid

edm_grid(steps, sigma_max=80.0, sigma_min=0.002, rho=7)

Karras et al.’s levels sigma_bar: even in sigma_bar^(1/rho), then 0. Abschnitt 17.5

embedding_rows

embedding_rows(table, X)

The rows X of table. Abschnitt 39.9

epsilon_greedy

epsilon_greedy(q, epsilon, rng)

Explore with probability epsilon, else act greedily on the values q. Abschnitt 14.3

evaluate

evaluate(env, policy, num_episodes, gamma=1.0, rng=None)

Mean discounted return of an acting policy over Monte Carlo episodes. Abschnitt 14.2

evaluate_accuracy

evaluate_accuracy(model, batches)

Fraction of the examples in batches that model classifies correctly. Abschnitt 9.5

evaluate_loss

evaluate_loss(net, data_iter, loss)

Evaluate the loss of a model on the given dataset. Abschnitt 39.9

extract

extract(filename, folder=None)

Extract a zip/tar file into folder. Abschnitt 39.9

f_valley

f_valley(x1, x2)

The ill-conditioned quadratic valley h1/2 x1^2 + h2/2 x2^2, with Abschnitt 9.1

fashion_feature_cnn

fashion_feature_cnn(X, y)

The feature network that judges Fashion-MNIST samples in this chapter. Abschnitt 17.4

fd_features

fd_features(cnn, imgs)

Features of gray images (n, 28, 28, 1) in [-1, 1]. Abschnitt 17.4

fid_score

fid_score(feat_p, feat_q)

Frechet distance between Gaussians fitted to two feature sets. Abschnitt 16.5

final_loss

final_loss(losses, k=100)

Mean of the last k losses; infinity if the run diverged. Abschnitt 9.5

fit_value

fit_value(ac, obs, target, num_steps=1)

Regress the value head on a fixed target: eq_value_baseline for nets. Abschnitt 14.9

flow_map_error

flow_map_error(u, teacher, x0, eps, s, t)

Per-example squared error of the average velocity u(x_t, s, t) against Abschnitt 17.8

flow_map_sample

flow_map_sample(u, x, steps, t_start=1.0)

Jump from x at t_start (1 is noise) to data at t = 0 in equal steps. Abschnitt 17.8

forward_np

forward_np(net, x)

net(x) for numpy x, as numpy, through one compiled forward per net Abschnitt 39.9

gan_loss_D

gan_loss_D(critic, real, fake)

Logistic critic loss -E[log sigma(D(x))] - E[log sigma(-D(x’))]: the Abschnitt 16.4

gan_loss_G

gan_loss_G(critic, real, fake)

Non-saturating generator loss -E[log sigma(D(x’))]; real is unused. Abschnitt 16.4

gd_2d

gd_2d(x1, x2, s1, s2, f_grad, eta)

One step of gradient descent in 2D; the state stays zero. Abschnitt 9.1

gelu_ish

gelu_ish(x)

The tanh approximation of GELU with rounded constants: a chain of Abschnitt 13.1

generator_step

generator_step(net_G, opt_G, loss_G, net_D, real, z, y=None)

One generator step on loss_G against the critic; return the loss. Abschnitt 16.4

get_airfoil

get_airfoil(batch_size=10, n=1500)

Load the standardized airfoil self-noise data as minibatches. Abschnitt 9.2.2

gpt2_tokenizer

gpt2_tokenizer()

GPT-2’s byte-level BPE tokenizer, assembled by tiktoken. Abschnitt 11.2

gpu

gpu(i=0)

Get a GPU device. Abschnitt 5.7

grad_sq_norm

grad_sq_norm(model, X, Y)

Squared norm of the gradient of ce_loss over all parameters. Abschnitt 9.8

gradient_penalty

gradient_penalty(D, X, fake, u, one_sided=False)

Mean (|D’(x)| - 1)^2 at the points u X + (1 - u) fake (inputs 1-D); Abschnitt 16.2

gray_features

gray_features(cnn, x)

Features of gray images (n, 28, 28, 1), clipped to [-1, 1]. Abschnitt 17.4

group_step

group_step(task, theta, K, reward, rng, lr=2.0)

verifier_step with the group-normalized weight (GRPO): the rewards Abschnitt 14.8

heads_to_batch

heads_to_batch(Z, num_heads)

(batch_size, T, num_heads * e) -> (batch_size * num_heads, T, e). Abschnitt 12.6

heun_sample

heun_sample(pred, x, sigma_bars)

Heun on d x_bar / d sigma_bar = eps: an Euler trial, then the average Abschnitt 17.5

init_timescales

init_timescales(layer, dt_min=0.001, dt_max=0.1, rngs)

Start a minGRU’s gates at the decays exp(-dt) of S4D. Abschnitt 12.4

js_mixtures

js_mixtures(mus_q, As_q, mus_p=mu_p, As_p=A_p)

JS(p, q) between two known mixtures, p the data by default, by Abschnitt 16.2

kernel_times

kernel_times(f, steps=10)

Device milliseconds per call of f, for every kernel that f runs. Abschnitt 13.1

kid_score

kid_score(feat_p, feat_q)

Unbiased MMD^2 between two feature sets, cubic polynomial kernel. Abschnitt 16.5

kneser_ney

kneser_ney(train, tokens, vocab_size, n=3)

Interpolated Kneser-Ney log-probabilities (nats) of each of tokens. Abschnitt 8.3

kv_cache_bytes

kv_cache_bytes(model, num_tokens, batch_size=1, bytes_per_elem=4)

Bytes of the keys and values of num_tokens positions in every block Abschnitt 11.3

langevin

langevin(score_fn, x, step, num_steps, key)

Langevin steps x <- x + step / 2 * score + sqrt(step) * noise. Abschnitt 17.1

linear_scan

linear_scan(a, b, h0=None)

All states of h_t = a_t * h_{t-1} + b_t; time is the second axis. Abschnitt 12.3

linear_schedule

linear_schedule(start, end, num_steps)

step -> value, interpolated from start to end, then held at end. Abschnitt 14.3

linreg

linreg(X, w, b)

The linear regression model. Abschnitt 39.9

lm_adamw

lm_adamw(lr=0.0, num_steps=1, warmup=0, weight_decay=0.0, max_norm=1.0)

The transformation of LMOptimizer, with its hyperparameters as state. Abschnitt 11.2

lm_decay_mask

lm_decay_mask(params)

Decay the weight matrices; exempt embeddings, gains, and biases. Abschnitt 11.2

lm_loss_sum

lm_loss_sum(graphdef, state, X, Y)

Summed next-token cross-entropy of a batch, and the model’s state. Abschnitt 9.5

lm_perplexity

lm_perplexity(model, batches)

Perplexity of a language model on the minibatches (X, Y) of batches. Abschnitt 9.5

load_array

load_array(data_arrays, batch_size, is_train=True)

Minibatches of JAX arrays, reshuffled each pass if is_train. Abschnitt 39.9

load_cifar10_arrays

load_cifar10_arrays()

CIFAR-10 on the default device, pixel values scaled to [-1, 1]. Abschnitt 39.9

load_data_bananas

load_data_bananas(batch_size)

Load the banana detection dataset. ?sec-object-detection-dataset

load_data_voc

load_data_voc(batch_size, crop_size)

Load the VOC semantic segmentation dataset. ?sec-semantic-segmentation

load_fashion_mnist_pm1

load_fashion_mnist_pm1(binary=False)

Fashion-MNIST (X, y, X_test, y_test), images in [-1, 1] or binary. Abschnitt 17.1

load_gpt2

load_gpt2()

GPT-2 small (124M) as a GPT with the released weights, in eval Abschnitt 11.2

load_pokemon

load_pokemon(resolution=64)

All Pokemon sprites as one (n, h, w, 3) array in [-1, 1]. Abschnitt 16.5

loss_by_position

loss_by_position(model, data)

Mean validation loss in nats at each position of the window. Abschnitt 12.1.4

lr_sweep

lr_sweep(make_model, make_tx, data, lrs, seed, num_steps=2000, evaluate=None, metric='score', every=None, verbose=True)

Train make_model(rngs=…) with the optax transformation make_tx(lr) Abschnitt 9.5

make_critic

make_critic(rngs)

Leaky-ReLU MLP; nnx.Linear gives LeCun-normal weights, zero biases. Abschnitt 16.2

make_mlp

make_mlp(sizes, act, rngs)

Linear layers of the given widths with the activation function act Abschnitt 16.1

make_pred

make_pred(net, path, kind)

pred(x, alpha, sigma) -> (x0, eps) from net(x, t) of a kind on path. Abschnitt 17.3

masked_softmax

masked_softmax(X, mask=None)

Softmax over the last axis with zero weight where mask is False. Abschnitt 10.2

mixture_logpdf

mixture_logpdf(x, mus, As)

Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k). Abschnitt 16.2

mixup

mixup(key, X, y, alpha)

Mix a minibatch with a shuffled copy; return both label sets. Abschnitt 7.6

mmd2_unbiased

mmd2_unbiased(K_pp, K_qq, K_pq)

Unbiased MMD^2 from the kernel matrices within p, within q, and Abschnitt 16.2

multibox_detection

multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5, pos_threshold=0.009999999)

Predict bounding boxes using non-maximum suppression. ?sec-anchor

multibox_prior

multibox_prior(data, sizes, ratios)

Generate anchor boxes with different shapes centered on each pixel. ?sec-anchor

multibox_target

multibox_target(anchors, labels)

Label anchor boxes using ground-truth bounding boxes. ?sec-anchor

nms

nms(boxes, scores, iou_threshold)

Sort confidence scores of predicted bounding boxes. ?sec-anchor

noise_scale

noise_scale(model, sample, b_small=16, b_big=2048, m=400)

Gradient-noise scale from the mean squared gradient norms of m Abschnitt 9.8

num_correct

num_correct(model, X, y)

Number of examples in (X, y) that model classifies correctly. Abschnitt 9.5

num_gpus

num_gpus()

Get the number of available GPUs. Abschnitt 5.7

num_params

num_params(model)

The number of trainable parameters. Abschnitt 7.5.1.1

ode_sample

ode_sample(pred, x, sigma_bars)

Euler (= DDIM) on d x_bar / d sigma_bar = eps, from x to data; x is the Abschnitt 17.3

offset_boxes

offset_boxes(anchors, assigned_bb, eps=1e-06)

Transform for anchor box offsets. ?sec-anchor

offset_inverse

offset_inverse(anchors, offset_preds)

Predict bounding boxes based on anchor boxes with predicted offsets. ?sec-anchor

on_grid

on_grid(runs, grid, col, smooth=1)

Resample per-episode rows (env step, value, …) onto an env-step Abschnitt 39.9

padded

padded(*arrays)

The arrays zero-padded along axis 0 to a shared bucket length, plus a Abschnitt 39.9

padding_mask

padding_mask(valid_lens, num_keys)

Boolean mask that is True for the first valid_lens keys. Abschnitt 10.2

pair_stats

pair_stats(net_D, real, fake, y=None)

Ranking accuracy P(D(x) > D(x’)) and mean rank weight Abschnitt 16.5

peak_memory

peak_memory(f, *args)

Temporary memory that XLA reserves to run jax.jit(f) on args, in Abschnitt 5.7

plain_sgd

plain_sgd(net, lr)

A plain SGD optimizer over net, one optax.sgd per learning rate. Abschnitt 39.9

plain_surrogate

plain_surrogate(rho, adv, epsilon)

The unclipped per-sample objective rho A. Abschnitt 15.2

plot

plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None, legend_loc=None)

Plot data points. Abschnitt 39.9

plot_curves

plot_curves(curves, xlabel, ylabel, smooth=1, reference=None, ylim=None, x=None, xscale='linear', yscale='linear', band='range')

One panel per call. curves maps a label to an array of shape Abschnitt 39.9

plot_hist

plot_hist(samples, xlabel, ylabel, bins=60, vlines=())

Overlaid histograms of samples (label -> values), dashed at vlines. Abschnitt 39.9

policy_evaluation

policy_evaluation(mdp, pi, num_iters)

Same sweep with the max replaced by an average under pi(a|s). Abschnitt 14.2

policy_objective

policy_objective(theta, P, r, gamma)

J(theta) = V(s0) of the softmax policy, a differentiable linear solve. Abschnitt 14.7

policy_step

policy_step(ac, obs, act, weight)

One ascent step on (1/n) sum_t w_t log pi(a_t|s_t) over a batch of Abschnitt 14.5

position_loss_sum

position_loss_sum(model, X, Y)

Loss in nats at each position, summed over the batch. Abschnitt 12.1.4

ppo_epochs

ppo_epochs(ac, obs, act, adv, logp_old, epsilon, num_epochs, entropy_coef=0.01, surrogate=clipped_surrogate)

num_epochs passes on the mean surrogate plus an entropy bonus, on one Abschnitt 15.2

precision_recall

precision_recall(feat_real, feat_gen, k=3, chunk=1000)

k-NN precision and recall of two feature sets: the fraction of each Abschnitt 16.5

pred_bar

pred_bar(pred, xb, r)

pred at x = alpha x_bar, sigma_bar = r; at r = inf, x_bar is noise. Abschnitt 17.3

q_learning

q_learning(seed, Q, visits, env, num_episodes, gamma, alpha=lambda n: 1 / (1 + 0.1 * n), epsilon=None)

Tabular Q-learning; updates Q in place, yields each episode’s return. Abschnitt 14.3

query_accuracy

query_accuracy(model, X, Y)

Fraction of queries answered correctly. Abschnitt 12.1.4

query_step

query_step(model, optimizer, X, Y)

One optimizer step on the cross-entropy at the last Y.shape[1] steps. Abschnitt 12.1.4

r1_r2_penalty

r1_r2_penalty(critic, real, fake)

Per-sample squared critic input gradients on real (R1) and fake (R2), Abschnitt 16.4

r3gan_step

r3gan_step(net_G, net_D, opt_G, opt_D, loss_D, loss_G, gamma, X, z, y, X2, z2, y2)

One critic step on X against G(z), one generator step on (X2, z2); Abschnitt 16.5

read_csv_labels

read_csv_labels(fname)

Read fname to return a filename to label dictionary. ?sec-kaggle-cifar10

read_data_bananas

read_data_bananas(is_train=True)

Read the banana detection dataset images and labels. ?sec-object-detection-dataset

read_voc_images

read_voc_images(voc_dir, is_train=True)

Read all VOC feature and label images. ?sec-semantic-segmentation

regression_loss

regression_loss(path, kind)

Squared error of net(x_t, t) against the target of a kind, t ~ U(0, 1). Abschnitt 17.2

reorg_test

reorg_test(data_dir)

Organize the testing set for data loading during prediction. ?sec-kaggle-cifar10

reorg_train_valid

reorg_train_valid(data_dir, labels, valid_ratio)

Split the validation set out of the original training set. ?sec-kaggle-cifar10

resnet18

resnet18(num_classes, in_channels=1, rngs)

ResNet-18 for small images: a 3x3 stem without max-pooling, He Abschnitt 13.6

rollout

rollout(env, policy, num_episodes, rng)

Collect complete episodes from policy(obs, rng) -> action as a Abschnitt 14.7

rope

rope(x, offset=0, base=10000.0, scale=None, tables=None)

Rotate feature pairs of x (…, num_steps, d) by position angles; Abschnitt 10.4

rope_tables

rope_tables(n, d, offset=0, base=10000.0, scale=None)

Cosines and sines, each (n, d/2), of the angles of the positions Abschnitt 10.4

rpgan_loss_D

rpgan_loss_D(critic, real, fake)

Relativistic pairing critic loss -E[log sigma(D(x) - D(x’))]. Abschnitt 16.3

rpgan_loss_G

rpgan_loss_G(critic, real, fake)

Non-saturating pairing loss for the generator. Abschnitt 16.3

run_seeds

run_seeds(train, num_seeds, **kwargs)

Run train(seed, **kwargs), a generator of curve points, per seed. Abschnitt 39.9

sample_mixture

sample_mixture(n, mus, As, rng)

n draws from the uniform mixture of Gaussians mu_k + z A_k. Abschnitt 16.2

sample_real

sample_real(key, images, n, labels=None)

Draw a training batch with random horizontal flips; return it with Abschnitt 16.5

scatter_panels

scatter_panels(samples, titles=None, data=None, lim=4.5, size=3.0)

Scatter 2-D point sets side by side on equal, shared axes. Abschnitt 17.1

set_axes

set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend, legend_loc=None)

Set the axes for matplotlib. legend_loc is a matplotlib legend Abschnitt 39.9

set_figsize

set_figsize(figsize=(3.5, 2.5))

Set the figure size for matplotlib. Abschnitt 39.9

set_log_ticks

set_log_ticks(axis)

Label all major ticks of a log axis in one format. Abschnitt 39.9

shared_adam

shared_adam(lr)

One optax.adam per learning rate, shared by all agents: compiled Abschnitt 39.9

shift_step

shift_step(critic_loss, gen_loss, gp, one_sided, G, D, opt_G, opt_D, X, Z, U)

One critic step per row of U, then one generator step; returns the Abschnitt 16.2

show_bboxes

show_bboxes(axes, bboxes, labels=None, colors=None)

Show bounding boxes. ?sec-anchor

show_gray

show_gray(imgs, num_rows, num_cols, titles=None, scale=1.0)

Show images (n, h, w, 1) in [-1, 1], or binary (n, h, w), in gray. Abschnitt 17.1

show_grid

show_grid(desc, values, policy=None, titles=None, diverging=False, fmt='{:.2f}')

A gridworld in the style of the chapter’s figures. Each cell is Abschnitt 39.9

show_heatmaps

show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5), cmap='Reds', cbar=True, xticklabels=None, yticklabels=None)

Show heatmaps of matrices; cbar is True (shared), ‘each’ or False. Abschnitt 39.9

show_images

show_images(imgs, num_rows, num_cols, titles=None, scale=1.5, cmap=None, vmin=None, vmax=None)

Plot a list of images (cmap colors single-channel images, on the Abschnitt 39.9

show_profile

show_profile(kernels, step_ms, rows=6)

Busy device time against the wall-clock time step_ms of a step, the Abschnitt 13.1

show_trace_2d

show_trace_2d(f, results)

Show the trace of 2D variables over the contours of f. Abschnitt 39.9

sinusoidal_encoding

sinusoidal_encoding(max_len, num_hiddens)

The (max_len, num_hiddens) table of sinusoidal position codes. Abschnitt 10.4

smooth

smooth(losses, k=25)

Means over consecutive blocks of k losses, for plotting. Abschnitt 9.5

squared_loss

squared_loss(y_hat, y)

Squared loss. Abschnitt 39.9

standardize

standardize(x, eps=1e-08)

Center a NumPy batch of weights and divide by its standard deviation Abschnitt 14.8

steps_to

steps_to(run, level, window)

Env steps at which the mean return of the last window rows of Abschnitt 15.1

steps_to_reach

steps_to_reach(losses, target, k=25)

First step at which the smoothed losses reach target; None if they Abschnitt 9.5

synthetic_data

synthetic_data(w, b, noise, n, key)

n examples with standard normal features and labels Xw + b + noise. Abschnitt 2.2

tabular_score

tabular_score(obs, act, w, pi)

sum_t w_t (e_{a_t} - pi(.|s_t)), each term added into row s_t: the Abschnitt 14.7

tanh_mlp

tanh_mlp(in_dim, hidden, out_dim, rngs)

A network with one tanh hidden layer. Abschnitt 14.9

text_table

text_table(make_model, arms, data, num_runs=2, num_steps=1000)

Train num_runs fresh models make_model(*args) for each arm (a name Abschnitt 12.1.4

tile_images

tile_images(imgs, num_rows)

Tile images (n, h, w, 3) in [-1, 1] into one (rows * h, cols * w, 3) Abschnitt 16.5

time_embedding

time_embedding(t, dim, freqs=(1.0, 64.0))

Sines and cosines of t at dim / 2 frequencies, geometric from freqs[0] Abschnitt 17.1

to_bf16

to_bf16(model)

Make the linear layers of model compute in bf16; parameters stay Abschnitt 13.4

tokenize

tokenize(lines, token='word')

Split text lines into word or character tokens. Abschnitt 39.9

train_2d

train_2d(trainer, f_grad, steps=20, **hparams)

Run a 2D update rule from (-5, -2) and return the iterates. Abschnitt 9.1

train_batch_ch13

train_batch_ch13(net, optimizer, X, y)

Train for a minibatch with JAX (defined in Chapter 13). ?sec-image-augmentation

train_ch13

train_ch13(net, train_iter, test_iter, optimizer, num_epochs)

Train a model with JAX (defined in Chapter 13). ?sec-image-augmentation

train_delayed_recall

train_delayed_recall(model, num_steps, blank_fillers=False)

Train with Adam at rate 0.003 on 1,500 fresh batches of 128 sequences Abschnitt 12.1.4

train_feature_cnn

train_feature_cnn(cnn, X, y, num_epochs=15, max_lr=0.003, batch_size=256, shift=0, seed=0)

Train on random horizontal flips, plus random shifts of up to shift Abschnitt 39.9

train_gan

train_gan(net_D, net_G, data_iter, num_epochs, latent_dim, lr_D, lr_G, step_G=update_G, seed=None, on_epoch=None, ema=None)

Alternate update_D and step_G over the minibatches with Adam Abschnitt 16.1

train_queries

train_queries(model, batch, num_steps, optimizer)

Train on fresh batches; the queries are the last Y.shape[1] steps. Abschnitt 12.1.4

train_r3gan

train_r3gan(net_G, net_D, loss_D, loss_G, gamma, num_steps, images, labels=None, eval_images=None, eval_labels=None, eval_size=256, batch_size=64, lr=0.0002, half_life=500, log_every=250, seed=None)

Train with Adam (beta_1 = 0), alternating critic_step and Abschnitt 16.5

train_recall

train_recall(model, pairs=(4, 8, 16, 32, 64), num_updates=2000, **task)

Train on associative recall (task: options of associative_recall) Abschnitt 12.6

train_regression

train_regression(model, loss_fn, batch_fn, num_steps, key, lr=0.001, cosine=False, ema_half_life=1000, chunk=500)

Adam on loss_fn(model, batch_fn(k1), k2) -> model, EMA model, losses. Abschnitt 17.1

train_reinforce_tabular

train_reinforce_tabular(ac, env, gamma, seed, num_updates=256, batch_episodes=16)

REINFORCE: a fresh batch from the current policy, every step of a Abschnitt 14.7

train_shift

train_shift(critic_loss, gen_loss, seed, gp=0.0, one_sided=False, theta0=6.0, steps=1500, n_critic=5, batch=256, lr_D=0.01, lr_G=0.01)

Fit x’ = theta + z to N(0, 1) by plain gradient steps on theta; return Abschnitt 16.2

train_step_gflops

train_step_gflops(net, loss_fn, shape, batch_size=128)

GFLOP of one training step, forward and backward, on a batch of zeros Abschnitt 17.7

train_steps

train_steps(model, data, optimizer, num_steps, stop=None)

Minimize the mean cross-entropy of the logits model(X) for the labels Abschnitt 9.5

train_text

train_text(model, data, lr=0.002, num_steps=1000)

Train a language model with LMOptimizer; return its validation loss Abschnitt 12.1.4

train_toy

train_toy(critic_loss, gen_loss, seed=0, steps=6000, batch=256, lr=0.001)

Fit a MixtureGenerator from (mu_0, A_0) to the data mixture, one Abschnitt 16.2

train_toy_step

train_toy_step(critic_loss, gen_loss, G, D, opt_G, opt_D, X, z, k)

A critic step (unless critic_loss is None), then a generator step. Abschnitt 16.2

truncate_pad

truncate_pad(line, num_steps, padding_token)

Truncate or pad sequences. Abschnitt 39.9

try_all_gpus

try_all_gpus()

Return all available GPUs, or [cpu(),] if no GPU exists. Abschnitt 5.7

try_gpu

try_gpu(i=0)

Return gpu(i) if exists, otherwise return cpu(). Abschnitt 5.7

update_D

update_D(X, Z, net_D, net_G, optimizer_D)

Update the critic; return its log loss summed over both batches Abschnitt 16.1

update_G

update_G(Z, net_D, net_G, optimizer_G)

Update the generator on the non-saturating loss; return its sum. Abschnitt 16.1

use_svg_display

use_svg_display()

Use the svg format to display a plot in Jupyter. Abschnitt 39.9

valley_grad

valley_grad(x1, x2)

Gradient of f_valley. Abschnitt 9.1

value_iteration

value_iteration(mdp, num_iters)

Sweep V <- max_a backup(V); return the whole history of iterates. Abschnitt 14.2

verifier_step

verifier_step(task, theta, K, reward, rng, weighting, lr=2.0)

One REINFORCE step on a VerifierTask: K responses per prompt, each Abschnitt 14.7

voc_colormap2label

voc_colormap2label()

Build the mapping from RGB to class indices for VOC labels. ?sec-semantic-segmentation

voc_label_indices

voc_label_indices(colormap, colormap2label)

Map any RGB values in VOC labels to their class indices. ?sec-semantic-segmentation

voc_rand_crop

voc_rand_crop(feature, label, height, width)

Randomly crop both feature and label images. ?sec-semantic-segmentation

windows

windows(corpus, batch_size, num_steps=128, sharding=None)

Endless minibatches of windows at random offsets, each position with Abschnitt 13.8

accuracy

accuracy(y_hat, y)

Compute the number of correct predictions. Abschnitt 39.9

add_to_class

add_to_class(Class)

Register functions as methods in created class. Abschnitt 2.4

as_metrics

as_metrics(out)

A step returns a loss or a dict of metrics; return a dict. Abschnitt 2.4

assign_anchor_to_bbox

assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5)

Assign closest ground-truth bounding boxes to anchor boxes. ?sec-anchor

bbox_to_rect

bbox_to_rect(bbox, color)

Convert bounding box to matplotlib format. ?sec-bbox

beam_search

beam_search(step_fn, prefix, num_tokens, beam_size=4, alpha=0.75, eos_id=None)

Length-normalized beam search (score = log P / len^alpha). Abschnitt 8.6.3

box_center_to_corner

box_center_to_corner(boxes)

Convert from (center, width, height) to (upper-left, lower-right). ?sec-bbox

box_corner_to_center

box_corner_to_center(boxes)

Convert from (upper-left, lower-right) to (center, width, height). ?sec-bbox

box_iou

box_iou(boxes1, boxes2)

Compute pairwise IoU across two lists of anchor or bounding boxes. ?sec-anchor

build_array_nmt

build_array_nmt(lines, vocab, num_steps)

Transform text sequences of machine translation into minibatches. Abschnitt 39.9

check_shape

check_shape(a, shape)

Check the shape of a tensor. Abschnitt 8.4.2

copyfile

copyfile(filename, target_dir)

Copy a file into a target directory. ?sec-kaggle-cifar10

corr2d

corr2d(X, K)

Compute 2D cross-correlation. Abschnitt 6.2

corrupt

corrupt(y, fraction, rng)

Replace each label, with probability fraction, by a random class. Abschnitt 4.5

cosine_warmup

cosine_warmup(t, num_steps, warmup_steps)

Learning-rate factor: linear warmup from 0, then a half-cosine to 0. Abschnitt 7.1

cpu

cpu()

Get the CPU device. Abschnitt 5.7

download

download(url, folder='../data', sha1_hash=None)

Download a file to folder and return the local filepath. Abschnitt 39.9

download_extract

download_extract(name, folder=None)

Download and extract a zip/tar file. Abschnitt 39.9

drop_path

drop_path(Y, p)

Zero each example of Y with probability p, rescale the rest. Abschnitt 7.6

evaluate_accuracy

evaluate_accuracy(net, data_iter)

Compute the accuracy for a model on a dataset. Abschnitt 39.9

evaluate_accuracy_gpu

evaluate_accuracy_gpu(net, data_iter, device=None)

Compute the accuracy for a model on a dataset using a GPU. Abschnitt 39.9

evaluate_accuracy_gpus

evaluate_accuracy_gpus(net, data_iter, split_f=d2l.split_batch)

Compute the accuracy for a model on a dataset using multiple GPUs. Abschnitt 13.6

evaluate_loss

evaluate_loss(net, data_iter, loss)

Evaluate the loss of a model on the given dataset. Abschnitt 39.9

extract

extract(filename, folder=None)

Extract a zip/tar file into folder. Abschnitt 39.9

get_dataloader_workers

get_dataloader_workers()

Use 4 processes to read the data except for Windows. Abschnitt 39.9

get_fashion_mnist_labels

get_fashion_mnist_labels(labels)

Return text labels for the Fashion-MNIST dataset. Abschnitt 39.9

gpu

gpu(i=0)

Get a GPU device. Abschnitt 5.7

kneser_ney

kneser_ney(train, tokens, vocab_size, n=3)

Interpolated Kneser-Ney log-probabilities (nats) of each of tokens. Abschnitt 8.3

linreg

linreg(X, w, b)

The linear regression model. Abschnitt 39.9

load_array

load_array(data_arrays, batch_size, is_train=True)

Construct a Gluon data iterator. Abschnitt 39.9

load_checkpoint

load_checkpoint(prefix, model, trainer=None, rng=None)

Restore the state written by save_checkpoint; return the metadata. Abschnitt 5.6

load_data_bananas

load_data_bananas(batch_size)

Load the banana detection dataset. ?sec-object-detection-dataset

load_data_fashion_mnist

load_data_fashion_mnist(batch_size, resize=None)

Download the Fashion-MNIST dataset and then load it into memory. Abschnitt 39.9

load_data_nmt

load_data_nmt(batch_size, num_steps, num_examples=600)

Return the iterator and the vocabularies of the translation dataset. Abschnitt 39.9

load_data_voc

load_data_voc(batch_size, crop_size)

Load the VOC semantic segmentation dataset. ?sec-semantic-segmentation

mixup

mixup(X, y, alpha)

Mix a minibatch with a shuffled copy; return both label sets. Abschnitt 7.6

multibox_detection

multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5, pos_threshold=0.009999999)

Predict bounding boxes using non-maximum suppression. ?sec-anchor

multibox_prior

multibox_prior(data, sizes, ratios)

Generate anchor boxes with different shapes centered on each pixel. ?sec-anchor

multibox_target

multibox_target(anchors, labels)

Label anchor boxes using ground-truth bounding boxes. ?sec-anchor

nms

nms(boxes, scores, iou_threshold)

Sort confidence scores of predicted bounding boxes. ?sec-anchor

num_gpus

num_gpus()

Get the number of available GPUs. Abschnitt 5.7

num_params

num_params(model)

The number of trainable parameters. Abschnitt 7.5.1.1

offset_boxes

offset_boxes(anchors, assigned_bb, eps=1e-06)

Transform for anchor box offsets. ?sec-anchor

offset_inverse

offset_inverse(anchors, offset_preds)

Predict bounding boxes based on anchor boxes with predicted offsets. ?sec-anchor

plot

plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None, legend_loc=None)

Plot data points. Abschnitt 39.9

predict_seq2seq

predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps, device, save_attention_weights=False)

Predict for sequence to sequence. Abschnitt 39.9

preprocess_nmt

preprocess_nmt(text)

Preprocess the English-French dataset. Abschnitt 39.9

read_csv_labels

read_csv_labels(fname)

Read fname to return a filename to label dictionary. ?sec-kaggle-cifar10

read_data_bananas

read_data_bananas(is_train=True)

Read the banana detection dataset images and labels. ?sec-object-detection-dataset

read_data_nmt

read_data_nmt()

Load the English-French dataset. Abschnitt 39.9

read_voc_images

read_voc_images(voc_dir, is_train=True)

Read all VOC feature and label images. ?sec-semantic-segmentation

reorg_test

reorg_test(data_dir)

Organize the testing set for data loading during prediction. ?sec-kaggle-cifar10

reorg_train_valid

reorg_train_valid(data_dir, labels, valid_ratio)

Split the validation set out of the original training set. ?sec-kaggle-cifar10

resnet18

resnet18(num_classes)

A slightly modified ResNet-18 model. Abschnitt 13.6

save_checkpoint

save_checkpoint(prefix, model, trainer, step, cfg=None, rng=None)

Replace each component of a resumable MXNet checkpoint. Abschnitt 5.6

set_axes

set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend, legend_loc=None)

Set the axes for matplotlib. legend_loc is a matplotlib legend Abschnitt 39.9

set_figsize

set_figsize(figsize=(3.5, 2.5))

Set the figure size for matplotlib. Abschnitt 39.9

set_log_ticks

set_log_ticks(axis)

Label all major ticks of a log axis in one format. Abschnitt 39.9

sgd

sgd(params, lr, batch_size)

Minibatch stochastic gradient descent. Abschnitt 39.9

show_bboxes

show_bboxes(axes, bboxes, labels=None, colors=None)

Show bounding boxes. ?sec-anchor

show_heatmaps

show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5), cmap='Reds', cbar=True, xticklabels=None, yticklabels=None)

Show heatmaps of matrices; cbar is True (shared), ‘each’ or False. Abschnitt 39.9

show_images

show_images(imgs, num_rows, num_cols, titles=None, scale=1.5, cmap=None, vmin=None, vmax=None)

Plot a list of images (cmap colors single-channel images, on the Abschnitt 39.9

split_batch

split_batch(X, y, devices)

Split X and y into multiple devices. Abschnitt 13.5

squared_loss

squared_loss(y_hat, y)

Squared loss. Abschnitt 39.9

synthetic_data

synthetic_data(w, b, noise, n)

n examples with standard normal features and labels Xw + b + noise. Abschnitt 2.2

tokenize

tokenize(lines, token='word')

Split text lines into word or character tokens. Abschnitt 39.9

tokenize_nmt

tokenize_nmt(text, num_examples=None)

Tokenize the English-French dataset. Abschnitt 39.9

train_batch_ch13

train_batch_ch13(net, features, labels, loss, trainer, devices, split_f=d2l.split_batch)

Train for a minibatch with multiple GPUs (defined in Chapter 13). ?sec-image-augmentation

train_ch13

train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices=d2l.try_all_gpus(), split_f=d2l.split_batch)

Train a model with multiple GPUs (defined in Chapter 13). ?sec-image-augmentation

train_ch6

train_ch6(net, train_iter, test_iter, num_epochs, lr, device)

Train a model with a GPU (defined in Chapter 6). Abschnitt 39.9

train_seq2seq

train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device)

Train a model for sequence to sequence. Abschnitt 39.9

truncate_pad

truncate_pad(line, num_steps, padding_token)

Truncate or pad sequences. Abschnitt 39.9

try_all_gpus

try_all_gpus()

Return all available GPUs, or [cpu(),] if no GPU exists. Abschnitt 5.7

try_gpu

try_gpu(i=0)

Return gpu(i) if exists, otherwise return cpu(). Abschnitt 5.7

use_svg_display

use_svg_display()

Use the svg format to display a plot in Jupyter. Abschnitt 39.9

voc_colormap2label

voc_colormap2label()

Build the mapping from RGB to class indices for VOC labels. ?sec-semantic-segmentation

voc_label_indices

voc_label_indices(colormap, colormap2label)

Map any RGB values in VOC labels to their class indices. ?sec-semantic-segmentation

voc_rand_crop

voc_rand_crop(feature, label, height, width)

Randomly crop both feature and label images. ?sec-semantic-segmentation