27.10 Довідник з API пакета d2l

У цьому підрозділі класи й функції пакета d2l наведено в абетковому порядку. Кожен запис містить посилання на відповідне визначення й пояснення в книжці. Згенеровані модулі також доступні в репозиторії книжки на GitHub.

27.10.1 Класи#

class APIRecording#

APIRecording(mode, record_dir, cost_cap_usd, providers)

The caches, the listing and the shared cost cap of one recording. In

  • 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. Підрозділ 27.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. Підрозділ 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. Підрозділ 14.9

class AdjointScan(torch.autograd.Function)#

linear_scan whose backward pass is a second scan, run backward. Підрозділ 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. Підрозділ 27.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. Підрозділ 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 Підрозділ 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 Підрозділ 17.7

  • encode(x)
  • forward(x)

class Averager#

Example-weighted means of batch metrics, summed on the device. Підрозділ 2.4

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

class BERTEncoder(nn.Module)#

BERTEncoder(vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout, max_len=1000, **kwargs)

BERT encoder. Підрозділ 18.8

  • forward(tokens, segments, valid_lens)

class BERTModel(nn.Module)#

BERTModel(vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout, max_len=1000)

The BERT model. Підрозділ 18.8

  • forward(tokens, segments, valid_lens=None, pred_positions=None)

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

  • 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 Підрозділ 8.2

  • pad()
  • bos()
  • eos()
  • train(text) — Learn vocab_size - 256 merges, most frequent pair first. Підрозділ 8.2
  • encode(text, allow_special=False)
  • decode(ids)
  • from_tiktoken(name) — Load a published bytes->rank table (e.g. 'gpt2') into our encoder. Підрозділ 8.2
  • to_tokens(ids)

class BackgroundLoad#

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

An async context manager that keeps lanes requests in flight

class BananasDataset(torch.utils.data.Dataset)#

BananasDataset(is_train)

A customized dataset to load the banana detection dataset. Підрозділ 20.6

class Batch#

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

A flat batch of transitions, plus the episode boundaries. Підрозділ 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. Підрозділ 14.8
  • reward_to_go(gamma) — G_t: the discounted return of the rest of its episode, by one scan. Підрозділ 14.8
  • truncation_bootstrap(gamma, V) — gamma^(T-t) (1 - term_T) V(s_T) for every step t of each episode: Підрозділ 14.9
  • td_target(bootstrap, gamma) — r_t + gamma (1 - terminated) V(s'), by a numpy bootstrap. Підрозділ 15.1
  • gae(value_fn, gamma, lam) — GAE(gamma, lam): the reward-to-go scan, run on the TD errors. Підрозділ 15.1
  • lambda_return(value_fn, gamma, lam) — The critic's target for GAE: the advantage plus the value it is Підрозділ 15.1

class Benchmark#

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

Time a callable: warmup, then device-synchronized average seconds. Підрозділ 5.7

class BookCorpus#

BookCorpus(manifest, docs, chunks, tag)

The book corpus under one chunking: chunks (a list of dicts in

  • 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

  • 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 < Підрозділ 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

  • 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. Підрозділ 3.3

  • validation_step(batch)
  • accuracy(Y_hat, Y, averaged=True) — Compute the fraction of correct predictions. Підрозділ 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

  • 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;

class DataModule(d2l.HyperParameters)#

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

The base class of data. Підрозділ 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 Підрозділ 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 Підрозділ 17.7

  • forward(X, c)

class Discriminator(nn.Module)#

Discriminator(resolution, base_ch)

Critic that mirrors the generator: conv + leaky ReLU + bilinear Підрозділ 16.5

  • phi(x)
  • forward(x)

class DocList(list)#

A list of Doc with the rows that failed to rebuild in .mismatches.

class DotProductAttention(nn.Module)#

DotProductAttention(dropout=0.0)

Scaled dot-product attention over the last two axes. Підрозділ 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 Підрозділ 16.5

  • update(model)

class EvalResult#

EvalResult(per_item, meta)

Per-item results of one model on one suite (per_item: task, item_id,

  • 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
  • load(path) — An EvalResult written by save.

class EvalSuite#

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

Evaluation tasks (EvalTask records, or ids of d2l.EVAL_TASKS) with

  • 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
  • from_manifest(name_or_path, batch_size=8) — The suite of a frozen manifest: a name in d2l.EVAL_SUITES or a JSON
  • to_manifest(path=None) — The suite as a JSON-ready manifest {'name', 'tasks'}; with path,

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

  • 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. Підрозділ 9.5

  • forward(X)

class FashionMNIST(d2l.DataModule)#

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

The Fashion-MNIST dataset. Підрозділ 3.2

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

class FeatureCNN(nn.Module)#

FeatureCNN(feature_dim=128, resolution=32)

Three conv blocks, global average pooling, and a linear head. Inputs Підрозділ 27.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. Підрозділ 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 Підрозділ 11.2

  • forward(X)
  • init_weights() — GPT-2's initialization of the linear layers: N(0, 0.02^2) weights and Підрозділ 11.2
  • generate(prefix, num_tokens, temperature=1.0, top_k=None) — Sample a continuation of the token-id list prefix. Підрозділ 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. Підрозділ 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. Підрозділ 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). Підрозділ 12.6
  • memory(X, Q, K, V, log_a) — Outputs of the decayed matrix memory of every head. X is unused here; Підрозділ 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, Підрозділ 14.9

  • forward(obs)

class GaussianMixture#

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

A mixture of isotropic Gaussians, exact at every noise level. Підрозділ 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. Підрозділ 17.1
  • summary(x) — Mode weights by nearest mean, stray fraction, spread of the rest. Підрозділ 17.1
  • velocity(x, t) — E[eps - x0 | x_t] on the linear path x_t = (1 - t) x0 + t eps. Підрозділ 17.2

class GaussianPath#

GaussianPath(alpha, sigma)

x_t = alpha(t) x0 + sigma(t) eps, data at t = 0 and noise at t = 1. Підрозділ 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. Підрозділ 17.2
  • rates(t) — The time derivatives (alpha'(t), sigma'(t)), by forward-mode AD. Підрозділ 17.2
  • target(kind, x0, eps, t) — The regression target of a kind: eps, x0, v, score or velocity. Підрозділ 17.2
  • x0_eps(kind, out, x, t) — The (x0, eps) that a prediction out of a kind implies at (x, t). Підрозділ 17.2
  • sigma_bars(steps) — sigma_bar = sigma / alpha on the grid of steps; inf where alpha = 0. Підрозділ 17.3
  • time_at(log_snr) — The time with a given log-SNR, by bisection (lambda_t falls in t). Підрозділ 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 Підрозділ 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), Підрозділ 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,

  • 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. Підрозділ 27.9

class IVFIndex#

IVFIndex(nlist, nprobe=1)

Inverted file index: the k-means cells of the training vectors; a

  • 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 Підрозділ 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. Підрозділ 6.6

  • weight_init(module)

class LinearRegression(d2l.Module)#

LinearRegression(lr)

Linear regression built from framework components. Підрозділ 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. Підрозділ 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

  • 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. Підрозділ 12.5

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

class MaskLM(nn.Module)#

MaskLM(vocab_size, num_hiddens, **kwargs)

The masked language model task of BERT. Підрозділ 18.8

  • forward(X, pred_positions)

class MaskedSoftmaxCELoss(nn.CrossEntropyLoss)#

The softmax cross-entropy loss with masks. Підрозділ 27.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. Підрозділ 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. Підрозділ 16.2

  • forward(z, k)
  • params_np()

class Module(nn.Module, d2l.HyperParameters)#

The base class of models. Підрозділ 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. Підрозділ 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 < Підрозділ 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, Підрозділ 10.3
  • merge_heads(X) — Reverse split_heads: (batch, num_heads, length, width) -> (batch, Підрозділ 10.3

class NextSentencePred(nn.Module)#

NextSentencePred(**kwargs)

The next sentence prediction task of BERT. Підрозділ 18.8

  • forward(X)

class NgramIndex#

NgramIndex(n=13)

Hashed word n-grams of indexed texts, for decontamination: a key is

  • 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. Підрозділ 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 Підрозділ 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. Підрозділ 14.5
  • act_greedy(obs, rng=None) — The most probable action; the same protocol as act. Підрозділ 14.5
  • log_prob_np(obs, act) — log pi(a|s) for numpy batches of states and actions, as numpy. Підрозділ 14.5
  • probs(num_states, num_actions) — pi(a|s) for every pair, as a (num_states, num_actions) numpy array. Підрозділ 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

  • forward(input_ids, attention_mask)

class ProductQuantizer#

ProductQuantizer(m, nbits=8)

Product quantization: a vector of d coordinates is cut into m

  • 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. Підрозділ 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. Підрозділ 27.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,

  • 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

  • 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
  • forward_cached(X, ks, vs, t) — Logits after the last of the new tokens X, which sit at positions
  • generate_cached(prefix, num_tokens, temperature=1.0, top_k=None) — Sample as generate does, but never recompute the prefix.

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,

  • 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. Підрозділ 8.4.6

  • forward(inputs, H=None)

class RNNLM(d2l.RNNLMScratch)#

The RNN-based language model implemented with high-level APIs. Підрозділ 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. Підрозділ 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. Підрозділ 8.4.2

  • forward(inputs, state=None)

class RandomGenerator#

RandomGenerator(sampling_weights)

Randomly draw among {1, ..., n} according to n sampling weights. Підрозділ 18.3

  • draw()

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. Підрозділ 12.1.4

  • forward(X)

class Recurrent(nn.Module)#

Recurrent(rnn)

A batch-first recurrent layer that returns only its outputs. Підрозділ 12.1.4

  • forward(X)

class ReplayBuffer#

ReplayBuffer(capacity, obs_dim)

A ring of transitions in preallocated numpy; sample() returns a Batch. Підрозділ 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. Підрозділ 15.5

class ReplayMiss(KeyError)#

A request that is not in the cache of a client in replay mode: a

class ResNeXtBlock(nn.Module)#

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

The ResNeXt block. Підрозділ 7.4

  • forward(X)

class Residual(nn.Module)#

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

The Residual block of ResNet models. Підрозділ 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. Підрозділ 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). Підрозділ 12.4

class SGD(d2l.HyperParameters)#

SGD(params, lr)

Minibatch stochastic gradient descent. Підрозділ 2.4

  • step()
  • zero_grad()

class SNLIDataset(torch.utils.data.Dataset)#

SNLIDataset(dataset, num_steps, vocab=None)

A customized dataset to load the SNLI dataset. Підрозділ 19.4

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 Підрозділ 12.5

  • log_coefficients(U) — Log-decays and writes, each of shape (batch_size, T, H, N). Підрозділ 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. Підрозділ 12.1.4

  • forward(X)
  • first_mixer_input(X) — What the first mixer reads: the normalized token embeddings. Підрозділ 12.3

class Shift(nn.Module)#

Shift(theta0)

The generator x' = theta + z. Підрозділ 16.2

  • forward(z)

class SoftmaxRegression(d2l.Classifier)#

SoftmaxRegression(num_outputs, lr)

The softmax regression model. Підрозділ 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 Підрозділ 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.

class SyntheticRegressionData(d2l.DataModule)#

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

Synthetic data for linear regression. Підрозділ 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]. Підрозділ 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 Підрозділ 14.2
  • policy_value(pi) — V^pi = (I - gamma P_pi)^{-1} r_pi exactly, for pi[s, a] the Підрозділ 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; Підрозділ 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. Підрозділ 8.2

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

class Timer#

Record multiple running times. Підрозділ 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. Підрозділ 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. Підрозділ 10.4
  • alibi(T, device) — ALiBi bias -m_h (i - j) of every head, (num_heads, T, T). Підрозділ 10.4
  • attend(blk, H) — Output of attention block blk on the stream H, and its weights. Підрозділ 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. Підрозділ 9.5

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

class TokenEmbedding#

TokenEmbedding(embedding_name)

Token Embedding.

class TokenShards#

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

Read-only access to a shard set written by write_shards: documents

  • 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

  • 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. Підрозділ 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. Підрозділ 2.4

  • prepare_data(data)
  • prepare_optimizer(model) — configure_optimizers may also return a learning-rate scheduler. Підрозділ 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 Підрозділ 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 Підрозділ 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

  • 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. Підрозділ 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. Підрозділ 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 Підрозділ 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

  • 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. Підрозділ 20.9

  • normalize_image(img)
  • filter(imgs)

class VerifierTask#

Four prompts, nine candidate responses shared by all of them, an Підрозділ 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. Підрозділ 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. Підрозділ 11.5

class Vocab#

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

Vocabulary for text. Підрозділ 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. Підрозділ 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:

class seeded#

seeded(seed)

In a with seeded(seed): block, PyTorch's CPU generator starts from Підрозділ 14.5

27.10.2 Функції#

accuracy#

accuracy(y_hat, y)

Compute the number of correct predictions. Підрозділ 27.9

add_to_class#

add_to_class(Class)

Register functions as methods in created class. Підрозділ 2.4

adjoint_scan#

adjoint_scan(a, b)

All states of h_t = a_t * h_{t-1} + b_t, differentiated by a scan. Підрозділ 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

align_uniform#

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

Wang and Isola's alignment, the mean squared distance between the

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. Підрозділ 17.3

anisotropy#

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

Mean cosine similarity between distinct rows of Z, over n_pairs

api_calls#

api_calls(calls_path)

The live attempts in a client's calls log (d2l.ChatAPI.calls_path)

api_committed#

api_committed(folders)

Totals over every arm in the manifest.json of each folder that has

api_cost#

api_cost(usage, price)

Cost in USD of one response, ((p - c) input + c cached_input +

api_recorded#

api_recorded(api)

Totals of a whole recording from a client's calls log: live calls,

api_unpack#

api_unpack(key)

Download a registered zip (sha1 checked) and unpack it once, into a

as_metrics#

as_metrics(out)

A step returns a loss or a dict of metrics; return a dict. Підрозділ 2.4

assert_key_absent#

assert_key_absent(roots, key)

Raise AssertionError if the bytes of key occur in any file under the

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. Підрозділ 20.4

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 Підрозділ 12.6

associative_scan#

associative_scan(combine, elems)

All prefixes of elems under an associative combine; time is axis 1. Підрозділ 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

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

barycentric#

barycentric(W)

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

batch_to_heads#

batch_to_heads(Y, batch_size)

(batch_size * num_heads, T, e) -> (batch_size, T, num_heads * e). Підрозділ 12.6

batched#

batched(f, X, batch_size=1000)

Apply f to X in batches, without gradients, and concatenate. Підрозділ 16.5

batchify#

batchify(data)

Return a minibatch of examples for skip-gram with negative sampling. Підрозділ 18.3

bbox_to_rect#

bbox_to_rect(bbox, color)

Convert bounding box to matplotlib format. Підрозділ 20.3

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). Підрозділ 8.6.3

benchmark_items#

benchmark_items()

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

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

binarize#

binarize(Z)

The signs of Z (N, m) as bits, eight per byte: uint8 (N, m / 8).

binary_f1#

binary_f1(y, pred)

F1 of boolean predictions against boolean labels (0 if none).

bind_hf_kernels#

bind_hf_kernels()

Route the linear-attention functions of Transformers' Gated DeltaNet

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

bleu#

bleu(pred_seq, label_seq, k)

Compute the BLEU. Підрозділ 12.2.2

block_runs#

block_runs(cells, classes)

(block, class) cells as text, runs of blocks per class in the order

bm25_tokenize#

bm25_tokenize(text, split_identifiers=True)

Lower-cased words and numbers of text; an identifier such as

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:

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

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

box_center_to_corner#

box_center_to_corner(boxes)

Convert from (center, width, height) to (upper-left, lower-right). Підрозділ 20.3

box_corner_to_center#

box_corner_to_center(boxes)

Convert from (upper-left, lower-right) to (center, width, height). Підрозділ 20.3

box_iou#

box_iou(boxes1, boxes2)

Compute pairwise IoU across two lists of anchor or bounding boxes. Підрозділ 20.4

bpb_from_nll#

bpb_from_nll(sum_nll_nats, n_bytes)

Bits per byte from a summed negative log-likelihood in nats and the

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

build_array_nmt#

build_array_nmt(lines, vocab, num_steps)

Transform text sequences of machine translation into minibatches. Підрозділ 27.9

bytes_read#

bytes_read(config, n, b=2)

Bytes a decode step reads at context n: the weights except the

c0_documents#

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

The c0 documents: the cached rebuild in cache_dir (default

cache_bytes#

cache_bytes(cache)

Bytes of the floating-point tensors reachable from a cache object,

cache_stream#

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

The stream after block layer at the positions >= 1 of windows

calibrate_labels#

calibrate_labels(logprobs, content_free_logprobs)

Contextual calibration: subtract the mean log-probabilities (M, L)

campaign_record#

campaign_record(spec, result, cfg)

The JSON record a finished proxy run leaves in a campaign file: its

causal_mask#

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

Boolean (queries, keys) mask, True where a query may see a key. Підрозділ 10.2

ce_loss#

ce_loss(model, X, Y)

Mean cross-entropy of the logits model(X) for the labels Y. Підрозділ 9.8

cfg#

cfg(net, c, gamma)

Classifier-free guidance: (x, t) -> u + gamma (u_c - u), u unlabeled. Підрозділ 17.4

char_fraction#

char_fraction(text, pattern)

The fraction of the non-space characters of text that match the

char_ngram_f1#

char_ngram_f1(a, b, n=5)

(precision, recall, F1) of the character n-grams of text a against

chat_batch#

chat_batch(api, requests, concurrency=8)

Send requests (dicts with 'messages', optionally 'replica' and request

chat_thinks#

chat_thinks(r)

Whether a chat result reasoned: reasoning tokens in its usage, or

check_closed_loop#

check_closed_loop(results, c)

Raise ValueError unless results can be one closed loop of c recorded

check_shape#

check_shape(a, shape)

Check the shape of a tensor. Підрозділ 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

chrf#

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

chrF (Popovic, 2015): character n-gram F-score. Підрозділ 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:

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. Підрозділ 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. Підрозділ 12.6

classify_failure#

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

The stage at which an answer failed: 'correct'; an unanswerable item

clean_ag_news#

clean_ag_news(titles)

AG News titles with the escapes left in them resolved: HTML

clipped_surrogate#

clipped_surrogate(rho, adv, epsilon)

PPO's per-sample objective eq_ppo_clip: min(rho A, clip(rho) A). Підрозділ 15.2

closed_loop_stats#

closed_loop_stats(results, c)

Throughput and latency of a closed loop that kept c requests in

cluster_resample#

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

Per replicate, the item indices of a resample of whole clusters

cohen_kappa#

cohen_kappa(a, b)

Cohen's kappa of two label arrays: agreement beyond what the two

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)

collect_hiddens#

collect_hiddens(model, input_ids)

Per layer, in execution order: the attention output, the residual

conditional#

conditional(net, c)

The field (x, t) -> net(x, t, c) with the labels c fixed. Підрозділ 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.

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),

containment#

containment(a, b)

The containment |A & B| / |A| of A in B (Broder); 0 if A is empty.

contam_documents#

contam_documents(plants, stream)

The documents of the planted set, doc_id -> text: each planted text

cooccurrence_counts#

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

Word-context counts within window positions as a symmetric

copyfile#

copyfile(filename, target_dir)

Copy a file into a target directory. Підрозділ 20.13

corr2d#

corr2d(X, K)

Compute 2D cross-correlation. Підрозділ 6.2

corrupt#

corrupt(y, fraction, rng)

Replace each label, with probability fraction, by a random class. Підрозділ 4.5

cosine_warmup#

cosine_warmup(t, num_steps, warmup_steps)

Learning-rate factor: linear warmup from 0, then a half-cosine to 0. Підрозділ 7.1

cost_of_half#

cost_of_half(cost, sw)

The cost at which a strength grid (cost and switched fraction per

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

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

cpu#

cpu()

Get the CPU device. Підрозділ 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 Підрозділ 16.4

cuda_graphed#

cuda_graphed(step, device, warmup=3)

Return a function that calls step(). On a CUDA device it runs step() Підрозділ 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. Підрозділ 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. Підрозділ 17.5

decay_mask#

decay_mask(log_a)

L[t, s] = a_{s+1} * ... * a_t for s <= t, and 0 for s > t. Підрозділ 12.6

decode_body#

decode_body(body, headers)

(text, charset, source) of an HTTP payload. The charset comes from

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. Підрозділ 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. Підрозділ 12.7

detect_lang#

detect_lang(text, k=1)

The top k (language, score) pairs of fastText's 176-language

detection_stats#

detection_stats(y, score, threshold)

Precision and recall of score > threshold as a detector of the

distinct_n#

distinct_n(texts, n=4)

The share of distinct word n-grams among all word n-grams of texts

docs_hash#

docs_hash(docs)

SHA-256 over the sorted (id, SHA-256 of the text) pairs: the content

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

download#

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

Download a file to folder and return the local filepath. Підрозділ 27.9

download_extract#

download_extract(name, folder=None)

Download and extract a zip/tar file. Підрозділ 27.9

download_keyed#

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

Download DATA_HUB[key] into root/key/ and return its local path.

drop_path#

drop_path(Y, p, training)

Zero each example of Y with probability p, rescale the rest. Підрозділ 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. Підрозділ 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

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,

edu_label_servers#

edu_label_servers(gpus=None, vllm=None)

One d2l.LocalChatServer per GPU (default: every visible GPU), each

effective_tokens#

effective_tokens(unique, epochs, r_star=15.4)

Effective data D' = U + U R* (1 - exp(-R / R*)) of epochs passes

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

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:

epsilon_greedy#

epsilon_greedy(q, epsilon, rng)

Explore with probability epsilon, else act greedily on the values q. Підрозділ 14.3

evaluate#

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

Mean discounted return of an acting policy over Monte Carlo episodes. Підрозділ 14.2

evaluate_accuracy#

evaluate_accuracy(model, batches)

Fraction of the examples in batches that model classifies correctly. Підрозділ 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. Підрозділ 27.9

evaluate_loss#

evaluate_loss(net, data_iter, loss)

Evaluate the loss of a model on the given dataset. Підрозділ 27.9

extend_vocab#

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

Add new_pieces to a Transformers tokenizer (as added tokens, which

extract#

extract(filename, folder=None)

Extract a zip/tar file into folder. Підрозділ 27.9

extract_answer#

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

The answer a generated text commits to, as a string, or None.

extract_page#

extract_page(job)

The extract cell's worker for one HTML response job = (path, offset,

extract_text#

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

The main text of a page, or None. 'naive': blocks with at least 40

f_valley#

f_valley(x1, x2)

The ill-conditioned quadratic valley h1/2 x1^2 + h2/2 x2^2, with Підрозділ 9.1

fan_in_init#

fan_in_init(module)

Fan-in normal weights with the leaky-ReLU gain, zero offsets. Підрозділ 16.5

fashion_feature_cnn#

fashion_feature_cnn(X, y)

The feature network that judges Fashion-MNIST samples in this chapter. Підрозділ 17.4

fd_features#

fd_features(cnn, imgs)

Features of gray images (n, 1, 28, 28) in [-1, 1], on the CPU. Підрозділ 17.4

fertility_table#

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

Per encoder and language: passages, UTF-8 bytes, tokens, bytes per

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

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.

fid_score#

fid_score(feat_p, feat_q)

Frechet distance between Gaussians fitted to two feature sets. Підрозділ 16.5

final_loss#

final_loss(losses, k=100)

Mean of the last k losses; infinity if the run diverged. Підрозділ 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

first_divergence#

first_divergence(errors, floor, factor=10.0)

The first (layer, capture point) in execution order whose median

fit_mixture_regression#

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

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

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'

fit_value#

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

Regress the value head on a fixed target: eq_value_baseline for nets. Підрозділ 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 Підрозділ 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. Підрозділ 17.8

fmt_ci#

fmt_ci(mean, ci, digits=3)

A value and its interval as text: 'mean [lo, hi]'.

format_mc#

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

A multiple-choice item as (prompt, choices). 'cloze': the prompt

frontier_area#

frontier_area(cost, sw, cap)

The area under the frontier from cost 0 to cap (linear between the

frontier_envelope#

frontier_envelope(cost, sw)

The monotone envelope of the points (cost, sw): the most switched at

fwedu_bucket#

fwedu_bucket(doc_id)

The bucket (0-255) of a FineWeb-Edu document: the first 32 bits of

fwedu_shards#

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

The reference shards of FineWeb-Edu under the reference tokenizer:

gan_loss_D#

gan_loss_D(critic, real, fake)

Logistic critic loss -E[log sigma(D(x))] - E[log sigma(-D(x'))]: the Підрозділ 16.4

gan_loss_G#

gan_loss_G(critic, real, fake)

Non-saturating generator loss -E[log sigma(D(x'))]; real is unused. Підрозділ 16.4

gd_2d#

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

One step of gradient descent in 2D; the state stays zero. Підрозділ 9.1

gelu_ish#

gelu_ish(x)

The tanh approximation of GELU with rounded constants: a chain of Підрозділ 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

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. Підрозділ 16.4

get_airfoil#

get_airfoil(batch_size=10, n=1500)

Load the standardized airfoil self-noise data as minibatches. Підрозділ 9.2.2

get_centers_and_contexts#

get_centers_and_contexts(corpus, max_window_size)

Return center words and context words in skip-gram. Підрозділ 18.3

get_dataloader_workers#

get_dataloader_workers()

Use 4 processes to read the data. Підрозділ 27.9

get_fashion_mnist_labels#

get_fashion_mnist_labels(labels)

Return text labels for the Fashion-MNIST dataset. Підрозділ 27.9

get_negatives#

get_negatives(all_contexts, vocab, counter, K)

Return noise words in negative sampling. Підрозділ 18.3

get_tokens_and_segments#

get_tokens_and_segments(tokens_a, tokens_b=None)

Get tokens of the BERT input sequence and their segment IDs. Підрозділ 18.8

gpt2_tokenizer#

gpt2_tokenizer()

GPT-2's byte-level BPE tokenizer, assembled by tiktoken. Підрозділ 11.2

gpu#

gpu(i=0)

Get a GPU device. Підрозділ 5.7

grad_clipping#

grad_clipping(net, theta)

Clip the gradient. Підрозділ 27.9

grad_sq_norm#

grad_sq_norm(model, X, Y)

Squared norm of the gradient of ce_loss over all parameters. Підрозділ 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); Підрозділ 16.2

group_step#

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

verifier_step with the group-normalized weight (GRPO): the rewards Підрозділ 14.8

hamming_scores#

hamming_scores(Qbits, Dbits)

The number of equal bits of each packed query and each packed

heads_to_batch#

heads_to_batch(Z, num_heads)

(batch_size, T, num_heads * e) -> (batch_size * num_heads, T, e). Підрозділ 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 Підрозділ 17.5

heuristic_filters#

heuristic_filters(text, cfg=None)

The reason codes of the rules in cfg (default GOPHER_CFG) that fire

hf_attention#

hf_attention(config, device)

The attention that runs config on device without an n x n mask:

hf_capacity#

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

The largest batch at n tokens (doubling, then bisection) and the

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

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

hf_kernels#

hf_kernels(model)

The code a model's attention and Gated DeltaNet layers run on a GPU

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:

hf_memory_table#

hf_memory_table(rows)

The memory columns of hf_measure's rows: the walker's bytes and the

hf_prefill#

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

Prefill the first n tokens: the output, the allocated bytes before,

hf_profile_steps#

hf_profile_steps(model, ids, rows)

Add one decode step's device time (busy and matrix products) and

hf_step_kernels#

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

Device milliseconds per kernel of one decode step, and the number of

hf_time_table#

hf_time_table(rows, beta_sheet)

The time columns of the profiled rows, in ms per decode step: wall

host_class#

host_class(url)

A coarse class of the host (edu_gov, wiki, forum, news, blog, shop,

html_skeleton#

html_skeleton(html, n=25)

The first n elements of a page's <body> as indented tag names, each

html_structure#

html_structure(html)

The structural content of a page, read from its HTML alone (no

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

init_cnn#

init_cnn(module)

Initialize weights for CNNs. Підрозділ 6.6

init_distributed#

init_distributed()

Join the process group of torchrun; return the rank, the number of Підрозділ 13.6

init_lecun#

init_lecun(module)

LeCun normal weights and zero biases for all linear, convolutional, Підрозділ 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. Підрозділ 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,

item_seed#

item_seed(seed, task_id, item_id)

A 63-bit seed for one item's random draws, from sha256 of

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

jaccard_exact#

jaccard_exact(a, b)

The resemblance |A & B| / |A | B| of two shingle collections taken

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 Підрозділ 16.2

json_agreement#

json_agreement(new, old)

How far two JSON-like results agree: the number of leaf values in

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

kernel_times#

kernel_times(f, steps=10)

Device milliseconds per call of f, for every kernel that f runs. Підрозділ 13.1

kid_score#

kid_score(feat_p, feat_q)

Unbiased MMD^2 between two feature sets, cubic polynomial kernel. Підрозділ 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:

kneser_ney#

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

Interpolated Kneser-Ney log-probabilities (nats) of each of tokens. Підрозділ 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 Підрозділ 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

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

langevin#

langevin(score_fn, x, step, num_steps)

Langevin steps x <- x + step / 2 * score + sqrt(step) * noise. Підрозділ 17.1

layer_errors#

layer_errors(ref, ours, skip_first=1)

Relative Frobenius error of each capture of collect_hiddens against a

lcp_array#

lcp_array(ids, sa)

lcp[i] = the length of the longest common prefix of the suffixes

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. Підрозділ 12.3

linear_schedule#

linear_schedule(start, end, num_steps)

step -> value, interpolated from start to end, then held at end. Підрозділ 14.3

linreg#

linreg(X, w, b)

The linear regression model. Підрозділ 27.9

listing_endpoint#

listing_endpoint(listing, model_id, provider)

The endpoint row of one provider of model_id in an OpenRouter listing

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

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

lm_free#

lm_free()

Return the memory of deleted models to the GPU.

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

lm_load_sae#

lm_load_sae(key, device=None)

The TopKSAE that lm_save_sae wrote, registered as DATA_HUB[key],

lm_peak#

lm_peak()

Peak GPU memory since the last call, as text: what tensors held, and

lm_perplexity#

lm_perplexity(model, batches)

Perplexity of a language model on the minibatches (X, Y) of batches. Підрозділ 9.5

lm_registered#

lm_registered(key)

Local path of the registered artifact DATA_HUB[key], or None while

lm_rerun#

lm_rerun(artifacts)

The measured results this run regenerates, from the environment

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.

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

lm_save_sae#

lm_save_sae(sae, tokens, name)

Write sae in fp16, with its config and its training-token count, as

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

lm_stream#

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

The activation at site (recorded by d2l.intervene, which stops the

lm_walk_docs#

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

Visit the rows of source = (repo, path, revision) in the order rows

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

lm_write_zip#

lm_write_zip(path, members)

A zip archive of members (name -> bytes), byte-identical for

load_array#

load_array(data_arrays, batch_size, is_train=True)

Construct a PyTorch data iterator. Підрозділ 27.9

load_checkpoint#

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

Restore the state written by save_checkpoint; return the raw dict. Підрозділ 5.6

load_cifar10_arrays#

load_cifar10_arrays()

CIFAR-10 on the GPU if there is one, pixel values scaled to [-1, 1]. Підрозділ 27.9

load_data_bananas#

load_data_bananas(batch_size)

Load the banana detection dataset. Підрозділ 20.6

load_data_fashion_mnist#

load_data_fashion_mnist(batch_size, resize=None)

Download the Fashion-MNIST dataset and then load it into memory. Підрозділ 27.9

load_data_imdb#

load_data_imdb(batch_size, num_steps=500)

Return data iterators and the vocabulary of the IMDb review dataset. Підрозділ 19.1

load_data_nmt#

load_data_nmt(batch_size, num_steps, num_examples=600)

Return the iterator and the vocabularies of the translation dataset. Підрозділ 27.9

load_data_ptb#

load_data_ptb(batch_size, max_window_size, num_noise_words)

Download the PTB dataset and then load it into memory. Підрозділ 18.3

load_data_snli#

load_data_snli(batch_size, num_steps=50)

Download the SNLI dataset and return data iterators and vocabulary. Підрозділ 19.4

load_data_voc#

load_data_voc(batch_size, crop_size)

Load the VOC semantic segmentation dataset. Підрозділ 20.9

load_data_wiki#

load_data_wiki(batch_size, max_len)

Load the WikiText-2 dataset. Підрозділ 18.9

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

load_fashion_mnist_pm1#

load_fashion_mnist_pm1(binary=False)

Fashion-MNIST (X, y, X_test, y_test), images in [-1, 1] or binary. Підрозділ 17.1

load_gpt2#

load_gpt2()

GPT-2 small (124M) as a GPT with the released weights, in eval Підрозділ 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

load_pokemon#

load_pokemon(resolution=64)

All Pokemon sprites as one (n, 3, h, w) tensor in [-1, 1]. Підрозділ 16.5

load_pool#

load_pool(path_or_key, name=None)

A token pool: a flat array of token ids (read-only memmap; every

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

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

logit_lens#

logit_lens(model, hidden)

The model's final norm and output head applied in fp32 to hidden

long_csv#

long_csv(T, axes, column)

The array T as CSV bytes, one row per entry: per axis a column that

loss_by_position#

loss_by_position(model, data)

Mean validation loss in nats at each position of the window. Підрозділ 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 Підрозділ 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,

make_critic#

make_critic()

Leaky-ReLU MLP with LeCun-normal weights and zero biases. Підрозділ 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

make_mlp#

make_mlp(sizes, act)

Linear layers of the given widths with the activation module act Підрозділ 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

make_pred#

make_pred(net, path, kind)

pred(x, alpha, sigma) -> (x0, eps) from net(x, t) of a kind on path. Підрозділ 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 Підрозділ 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

masked_softmax#

masked_softmax(X, mask=None)

Softmax over the last axis with zero weight where mask is False. Підрозділ 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

minhash_signature#

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

The MinHash signature, a (k,) uint64 array, of a shingle collection:

mix_pools#

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

(pools, val), each {domain: TokenPool}, of a MIX_CONFIGS entry c:

mix_run_specs#

mix_run_specs(c)

The run design of a MIX_CONFIGS entry c, in launch order: the

mixture_logpdf#

mixture_logpdf(x, mus, As)

Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k). Підрозділ 16.2

mixup#

mixup(X, y, alpha)

Mix a minibatch with a shuffled copy; return both label sets. Підрозділ 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

mmd2_unbiased#

mmd2_unbiased(K_pp, K_qq, K_pq)

Unbiased MMD^2 from the kernel matrices within p, within q, and Підрозділ 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. Підрозділ 20.4

multibox_prior#

multibox_prior(data, sizes, ratios)

Generate anchor boxes with different shapes centered on each pixel. Підрозділ 20.4

multibox_target#

multibox_target(anchors, labels)

Label anchor boxes using ground-truth bounding boxes. Підрозділ 20.4

naive_blocks#

naive_blocks(page)

The text blocks of a page, split at block-level tags, as (text,

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

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

nms#

nms(boxes, scores, iou_threshold)

Sort confidence scores of predicted bounding boxes. Підрозділ 20.4

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

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 Підрозділ 9.8

normalize_url#

normalize_url(url)

A URL in the form the validation split deduplicates on: scheme and

num_gpus#

num_gpus()

Get the number of available GPUs. Підрозділ 5.7

num_params#

num_params(model)

The number of trainable parameters. Підрозділ 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 Підрозділ 17.3

offset_boxes#

offset_boxes(anchors, assigned_bb, eps=1e-06)

Transform for anchor box offsets. Підрозділ 20.4

offset_inverse#

offset_inverse(anchors, offset_preds)

Predict bounding boxes based on anchor boxes with predicted offsets. Підрозділ 20.4

on_grid#

on_grid(runs, grid, col, smooth=1)

Resample per-episode rows (env step, value, ...) onto an env-step Підрозділ 27.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

padding_mask#

padding_mask(valid_lens, num_keys)

Boolean mask that is True for the first valid_lens keys. Підрозділ 10.2

pair_stats#

pair_stats(net_D, real, fake, y=None)

Ranking accuracy P(D(x) > D(x')) and mean rank weight Підрозділ 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]

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

pass_at_k#

pass_at_k(n, c, k)

Unbiased pass@k from n samples of which c are correct: the

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

peak_memory#

peak_memory(f, *args)

Extra peak GPU memory allocated by f(*args), in bytes. Підрозділ 5.7

percentile_ci#

percentile_ci(values, alpha=0.05, names=None)

Percentile endpoints of bootstrap replicates (along axis 0), over

plain_sgd#

plain_sgd(net, lr)

A plain SGD optimizer over the parameters of net. Підрозділ 27.9

plain_surrogate#

plain_surrogate(rho, adv, epsilon)

The unclipped per-sample objective rho A. Підрозділ 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. Підрозділ 27.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 Підрозділ 27.9

plot_hist#

plot_hist(samples, xlabel, ylabel, bins=60, vlines=())

Overlaid histograms of samples (label -> values), dashed at vlines. Підрозділ 27.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); Підрозділ 27.9

policy_evaluation#

policy_evaluation(mdp, pi, num_iters)

Same sweep with the max replaced by an average under pi(a|s). Підрозділ 14.2

policy_objective#

policy_objective(theta, P, r, gamma)

J(theta) = V(s0) of the softmax policy, a differentiable linear solve. Підрозділ 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 Підрозділ 14.5

pool_hidden#

pool_hidden(hidden, attention_mask, mode)

One vector per sequence from hidden states (B, T, m): the first

ppmi#

ppmi(counts, alpha=1.0, shift=0.0)

Positive (shifted) PMI of a count matrix as a scipy.sparse.csr_matrix:

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 Підрозділ 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 Підрозділ 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. Підрозділ 17.3

predict_sentiment#

predict_sentiment(net, vocab, sequence)

Predict the sentiment of a text sequence. Підрозділ 19.2

predict_seq2seq#

predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps, device, save_attention_weights=False)

Predict for sequence to sequence. Підрозділ 27.9

predict_snli#

predict_snli(net, vocab, premise, hypothesis)

Predict the logical relationship between the premise and hypothesis. Підрозділ 19.5

preprocess_nmt#

preprocess_nmt(text)

Preprocess the English-French dataset. Підрозділ 27.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

print_wrapped(*args, width=76)

Print like print, folding each line to the width of a page. Підрозділ 8.2

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

proxy_flops#

proxy_flops(cfg, tokens, n_params)

Training FLOP of a proxy run: 6 N D for the parameters plus

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. Підрозділ 14.3

quadratic_kappa#

quadratic_kappa(a, b, k=6)

Quadratic-weighted kappa of two integer scores in 0..k-1: one minus

query_accuracy#

query_accuracy(model, X, Y)

Fraction of queries answered correctly. Підрозділ 12.1.4

qwen3_gpt_kwargs#

qwen3_gpt_kwargs(cfg)

Qwen3GPT's arguments from a Qwen3 configuration (a dict or a

qwen3_rope_permutation#

qwen3_rope_permutation(head_dim)

Index idx with idx[2i] = i and idx[2i + 1] = i + head_dim / 2: taking

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

r1_r2_penalty#

r1_r2_penalty(critic, real, fake)

Per-sample squared critic input gradients on real (R1) and fake (R2), Підрозділ 16.4

r2_tokenizer#

r2_tokenizer(raw=False)

The reference tokenizer (artifact lm-r2-tokenizer-v1; its file is

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,

rag_judge_servers#

rag_judge_servers(gpus=None, vllm=None)

One d2l.LocalChatServer per GPU (default: every visible GPU), each

rag_prompt#

rag_prompt(question, hits, abstain=ABSTAIN)

Chat messages asking for an answer from numbered passages (hits: Hit

rank_auc#

rank_auc(y, s)

ROC AUC of scores s for boolean labels y (Mann-Whitney, ties at

read_conllu#

read_conllu(path, stride, max_words)

Every stride-th sentence of a CoNLL-U file, up to max_words words:

read_csv_labels#

read_csv_labels(fname)

Read fname to return a filename to label dictionary. Підрозділ 20.13

read_data_bananas#

read_data_bananas(is_train=True)

Read the banana detection dataset images and labels. Підрозділ 20.6

read_data_nmt#

read_data_nmt()

Load the English-French dataset. Підрозділ 27.9

read_docs#

read_docs(path)

The documents of a file written by write_docs, as a list of Doc

read_imdb#

read_imdb(data_dir, is_train)

Read the IMDb review dataset text sequences and labels. Підрозділ 19.1

read_jsonl#

read_jsonl(path)

A file of JSON lines as a DataFrame, one row per line, values with

read_ptb#

read_ptb()

Load the PTB dataset into a list of text lines. Підрозділ 18.3

read_snli#

read_snli(data_dir, is_train)

Read the SNLI dataset into premises, hypotheses, and labels. Підрозділ 19.4

read_voc_images#

read_voc_images(voc_dir, is_train=True)

Read all VOC feature and label images. Підрозділ 20.9

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

record_field_probe#

record_field_probe(path, endpoints, local_name, listing, providers, **kwargs)

Probe every endpoint at once (name -> (client, base, on, off,

registered_domain#

registered_domain(url)

The registered domain of a URL (example.co.uk for

regression_loss#

regression_loss(path, kind)

Squared error of net(x_t, t) against the target of a kind, t ~ U(0, 1). Підрозділ 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

reorg_test#

reorg_test(data_dir)

Organize the testing set for data loading during prediction. Підрозділ 20.13

reorg_train_valid#

reorg_train_valid(data_dir, labels, valid_ratio)

Split the validation set out of the original training set. Підрозділ 20.13

repeated_spans#

repeated_spans(ids, sa, lcp, min_len)

The maximal repeats of at least min_len tokens, as (start, length,

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,

request_hash#

request_hash(base_url, model, messages, params, replica=0)

sha256 of the canonical JSON (sorted keys, no whitespace, UTF-8) of

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

resnet18#

resnet18(num_classes, in_channels=1)

ResNet-18 for small images: a 3x3 stem without max-pooling, He Підрозділ 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

rollout#

rollout(env, policy, num_episodes, rng)

Collect complete episodes from policy(obs, rng) -> action as a Підрозділ 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; Підрозділ 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 Підрозділ 10.4

rpgan_loss_D#

rpgan_loss_D(critic, real, fake)

Relativistic pairing critic loss -E[log sigma(D(x) - D(x'))]. Підрозділ 16.3

rpgan_loss_G#

rpgan_loss_G(critic, real, fake)

Non-saturating pairing loss for the generator. Підрозділ 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

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

run_seeds#

run_seeds(train, num_seeds, **kwargs)

Run train(seed, **kwargs), a generator of curve points, per seed. Підрозділ 27.9

sae_acts#

sae_acts(sae, H, feats, chunk=2048)

The activations of the features feats of sae on H (docs, positions,

sae_fire_rate#

sae_fire_rate(sae, H, chunk=2048)

The fraction of the positions of H (..., d) where each feature of

sae_metrics#

sae_metrics(sae, model, token_batches, layer)

L0, FVU, loss recovered and firing density of sae on the stream

safetensors_header#

safetensors_header(model_id, revision=None, timeout=30)

Shape and dtype of every tensor of a Hub checkpoint, read by HTTP

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

sample_mixture#

sample_mixture(n, mus, As, rng)

n draws from the uniform mixture of Gaussians mu_k + z A_k. Підрозділ 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

sample_real#

sample_real(images, n, labels=None)

Draw a training batch with random horizontal flips; return it with Підрозділ 16.5

save_checkpoint#

save_checkpoint(path, model, optimizer, step, cfg=None, rng=None)

Atomically write a resumable training checkpoint. Підрозділ 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. Підрозділ 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,

scrub_pii#

scrub_pii(text)

Replace email addresses by <EMAIL> and public IPv4 and IPv6

scurve#

scurve(s, b, r)

The probability that a pair of Jaccard s becomes a candidate under b

sequence_mask#

sequence_mask(X, valid_len, value=0)

Mask irrelevant entries in sequences. Підрозділ 27.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 Підрозділ 27.9

set_figsize#

set_figsize(figsize=(3.5, 2.5))

Set the figure size for matplotlib. Підрозділ 27.9

set_log_ticks#

set_log_ticks(axis)

Label all major ticks of a log axis in one format. Підрозділ 27.9

sgd#

sgd(params, lr, batch_size)

Minibatch stochastic gradient descent. Підрозділ 27.9

sgns_loss#

sgns_loss(v, u, centers, contexts_negatives, labels, masks)

Skip-gram with negative sampling: the binary cross-entropy of the

shingles#

shingles(text, n=5)

The word n-grams of text as strings (the MinHash specification):

show_bboxes#

show_bboxes(axes, bboxes, labels=None, colors=None)

Show bounding boxes. Підрозділ 20.4

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. Підрозділ 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 Підрозділ 27.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. Підрозділ 27.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 Підрозділ 27.9

show_kernels#

show_kernels(kernels, rows=4)

The kernels of a decode step with the most device time: ms and share

show_profile#

show_profile(kernels, step_ms, rows=6)

Busy device time against the wall-clock time step_ms of a step, the Підрозділ 13.1

show_trace_2d#

show_trace_2d(f, results)

Show the trace of 2D variables over the contours of f. Підрозділ 27.9

sinusoidal_encoding#

sinusoidal_encoding(max_len, num_hiddens)

The (max_len, num_hiddens) table of sinusoidal position codes. Підрозділ 10.4

smooth#

smooth(losses, k=25)

Means over consecutive blocks of k losses, for plotting. Підрозділ 9.5

sp_train#

sp_train(texts, model_type, vocab_size, **kw)

A SentencePiece model trained on texts (one input line per line of

span_f1#

span_f1(pred_tags, gold_tags, id2label)

Entity-level precision, recall and F1 of IOB2 tag sequences (a list

spearman_eval#

spearman_eval(embeddings, vocab, pairs, n_boot=2000, seed=0)

Spearman correlation between the cosine similarities of embeddings

squared_loss#

squared_loss(y_hat, y)

Squared loss. Підрозділ 27.9

standardize#

standardize(x, eps=1e-08)

Center a NumPy batch of weights and divide by its standard deviation Підрозділ 14.8

steps_to#

steps_to(run, level, window)

Env steps at which the mean return of the last window rows of Підрозділ 15.1

steps_to_reach#

steps_to_reach(losses, target, k=25)

First step at which the smoothed losses reach target; None if they Підрозділ 9.5

structure_recall#

structure_recall(html, text)

Recall of a page's structural content in an extracted text: the

subsample#

subsample(sentences, vocab)

Subsample high-frequency words. Підрозділ 18.3

subset_ids#

subset_ids(n_total, n, seed=0)

Row indices of a seeded subset of n of n_total items: the first n

suffix_array#

suffix_array(ids)

The suffix array of an integer sequence by prefix doubling: sa[i] is

synth_metrics#

synth_metrics(src, out)

Fidelity of a rewrite out of src: copy_rate, the Jaccard similarity

synthetic_data#

synthetic_data(w, b, noise, n)

n examples with standard normal features and labels Xw + b + noise. Підрозділ 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 Підрозділ 14.7

tanh_mlp#

tanh_mlp(in_dim, hidden, out_dim)

A network with one tanh hidden layer. Підрозділ 14.9

temperature_weights#

temperature_weights(sizes, alpha)

Sampling probabilities p_i proportional to n_i ** alpha: alpha = 1

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 Підрозділ 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) Підрозділ 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] Підрозділ 17.1

token_byte_lengths#

token_byte_lengths(tokenizer)

np.ndarray of the UTF-8 bytes each token id stands for (0 for

tokenize#

tokenize(lines, token='word')

Split text lines into word or character tokens. Підрозділ 27.9

tokenize_nmt#

tokenize_nmt(text, num_examples=None)

Tokenize the English-French dataset. Підрозділ 27.9

torchrun#

torchrun(script, nproc, *args, env=None)

Run Python source in nproc processes; return their JSON lines. Підрозділ 13.6

train_2d#

train_2d(trainer, f_grad, steps=20, **hparams)

Run a 2D update rule from (-5, -2) and return the iterates. Підрозділ 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). Підрозділ 20.1

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). Підрозділ 20.1

train_ch6#

train_ch6(net, train_iter, test_iter, num_epochs, lr, device)

Train a model with a GPU (defined in Chapter 6). Підрозділ 27.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 Підрозділ 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 Підрозділ 27.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 Підрозділ 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,

train_queries#

train_queries(model, batch, num_steps, optimizer, scheduler=None)

Train on fresh batches; the queries are the last Y.shape[1] steps. Підрозділ 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 Підрозділ 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) Підрозділ 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). Підрозділ 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 Підрозділ 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

train_seq2seq#

train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device)

Train a model for sequence to sequence. Підрозділ 27.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 Підрозділ 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 Підрозділ 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 Підрозділ 9.5

train_text#

train_text(model, data, lr=0.002, num_steps=1000)

Train a language model with LMOptimizer; return its validation loss Підрозділ 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 Підрозділ 16.2

truncate_embeddings#

truncate_embeddings(Z, dim)

The first dim coordinates of each row of Z, rescaled to unit length.

truncate_pad#

truncate_pad(line, num_steps, padding_token)

Truncate or pad sequences. Підрозділ 27.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

try_all_gpus#

try_all_gpus()

Return all available GPUs, or [cpu(),] if no GPU exists. Підрозділ 5.7

try_gpu#

try_gpu(i=0)

Return gpu(i) if exists, otherwise return cpu(). Підрозділ 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

union_find_clusters#

union_find_clusters(n, pairs)

Connected components of n items under pairs, by union-find (path

update_D#

update_D(X, Z, net_D, net_G, trainer_D)

Update the critic; return its log loss summed over both batches Підрозділ 16.1

update_G#

update_G(Z, net_D, net_G, trainer_G)

Update the generator on the non-saturating loss; return its sum. Підрозділ 16.1

use_svg_display#

use_svg_display()

Use the svg format to display a plot in Jupyter. Підрозділ 27.9

valley_grad#

valley_grad(x1, x2)

Gradient of f_valley. Підрозділ 9.1

value_iteration#

value_iteration(mdp, num_iters)

Sweep V <- max_a backup(V); return the whole history of iterates. Підрозділ 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 Підрозділ 14.7

viterbi_segment#

viterbi_segment(text, logp, max_len, unk=None)

The most probable segmentation of text into pieces of logp (piece

voc_colormap2label#

voc_colormap2label()

Build the mapping from RGB to class indices for VOC labels. Підрозділ 20.9

voc_label_indices#

voc_label_indices(colormap, colormap2label)

Map any RGB values in VOC labels to their class indices. Підрозділ 20.9

voc_rand_crop#

voc_rand_crop(feature, label, height, width)

Randomly crop both feature and label images. Підрозділ 20.9

warc_record_at#

warc_record_at(path, offset, length)

The WarcRecord stored in bytes offset..offset+length-1 of a local

wilson_ci#

wilson_ci(k, n, z=1.96)

Wilson score interval for a binomial proportion k / n.

windows#

windows(corpus, batch_size, num_steps=128)

Endless minibatches of windows at random offsets, each position with Підрозділ 13.8

word_windows#

word_windows(text, size=128, stride=64)

Windows of size whitespace-separated words every stride words, the

write_api_manifests#

write_api_manifests(clients, record_dir)

Append this session to the manifest.json of every cache folder under

write_docs#

write_docs(path, docs)

Write documents (Doc or dicts with Doc's fields) as gzip-compressed

write_jsonl#

write_jsonl(path, records)

Write records (dicts) as JSON lines.

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|