27.10 d2l API 레퍼런스
이 절은 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 thatadd(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. ?sec-bert
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. ?sec-bert
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절
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. ?sec-object-detection-dataset
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 setsearch_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; withrelease()— 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, headforward(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 eventmodels()— 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. Idssummary(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 theload(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 byitems(task_id)— The items of one task in subset order: dicts with the item’srun(model, tokenizer, seed=0, cache_dir=None, rerun=False, sandbox=False)— Score every item and return an EvalResult. With cache_dir, resultsfrom_manifest(name_or_path, batch_size=8)— The suite of a frozen manifest: a name in d2l.EVAL_SUITES or a JSONto_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절
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절
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절
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 predictionoutof 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절
save_hyperparameters(ignore=None)— Save function arguments into instance attributes. 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. ?sec-bert
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 metricsvalidation_step(batch)— The mean loss on one minibatch of validation data, or a dict ofconfigure_optimizers()apply_init(inputs, init=None)— Run a dry pass to fix lazy shapes, then applyinit. 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. ?sec-bert
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 theadc_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 nextshowstarts a new figure.draw(x, y, label)— Append the point (x, y) to the curve calledlabel.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, kvforward_cached(X, ks, vs, t)— Logits after the last of the new tokens X, which sit at positionsgenerate_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): theanswer(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. ?sec-word2vec-data
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. ?sec-natural-language-inference-and-dataset
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 samplersample(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절
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; equalencode(x)decode(z)forward(x)loss(x, dead=None, k_aux=256)— Squared error normalized by the batch variance; the auxiliarynormalize_decoder_()— Project each decoder column onto the unit sphere (columns alreadyremove_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_optimizersmay also return a learning-rate scheduler. 2.4절fit(model, data)record(split, metrics, x)fit_epoch()validate()evaluate(model, data, train=False)— Metrics ofmodelon the validation data ofdata(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. ?sec-semantic-segmentation
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 atstarts.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절
class Accumulator
Accumulator(n)For accumulating sums over n variables. 27.9절
add(*args)reset()
class Animator
Animator(xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1, figsize=(3.5, 2.5))For plotting data in animation. 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 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(keras.layers.Layer)
BERTEncoder(vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout, max_len=1000, **kwargs)BERT encoder. ?sec-bert
call(tokens, segments, valid_lens, training=False, **kwargs)
class BERTModel(keras.Model)
BERTModel(vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout, max_len=1000)The BERT model. ?sec-bert
call(tokens, segments, valid_lens=None, pred_positions=None, training=False, **kwargs)
class BPETokenizer
BPETokenizer(vocab_size=1024, pattern=None, specials=('<pad>', '<bos>', '<eos>'))Byte-level BPE tokenizer trained by iterated most-frequent-pair 8.2절
class BananasDataset
BananasDataset(is_train)A customized dataset to load the banana detection dataset. ?sec-object-detection-dataset
class Benchmark
Benchmark(f, warmup=3, repeats=10, desc='time')Time a callable: warmup, then device-synchronized average seconds. 5.7절
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 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 FashionMNIST(d2l.DataModule)
FashionMNIST(batch_size=64, resize=(28, 28))The Fashion-MNIST dataset. 3.2절
class HyperParameters
The base class of hyperparameters. 27.9절
save_hyperparameters(ignore=None)— Save function arguments into instance attributes. 27.9절
class LeNet(d2l.Classifier)
LeNet(lr=0.1, num_classes=10)The layout of LeNet-5, with sigmoid activations and average pooling. 6.6절
class LinearRegression(d2l.Module)
LinearRegression(lr)Linear regression built from framework components. 2.5절
loss(y_hat, y)configure_optimizers()get_w_b()
class LinearRegressionScratch(d2l.Module)
LinearRegressionScratch(num_inputs, lr, sigma=0.01)The linear regression model implemented from scratch. 2.4절
forward(X)loss(y_hat, y)configure_optimizers()
class MaskLM(keras.layers.Layer)
MaskLM(vocab_size, num_hiddens, **kwargs)The masked language model task of BERT. ?sec-bert
call(X, pred_positions, **kwargs)
class MaskedSoftmaxCELoss(tf.keras.losses.Loss)
MaskedSoftmaxCELoss(valid_len)The softmax cross-entropy loss with masks. 27.9절
call(label, pred)
class Module(tf.keras.Model, d2l.HyperParameters)
The base class of models. 2.4절
loss(y_hat, y)forward(X)call(X, *args, training=None, **kwargs)training_step(batch)— The mean loss on one minibatch, or a dict of batch-mean metricsvalidation_step(batch)— The mean loss on one minibatch of validation data, or a dict ofconfigure_optimizers()
class NextSentencePred(keras.layers.Layer)
NextSentencePred(**kwargs)The next sentence prediction task of BERT. ?sec-bert
call(X, **kwargs)
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 nextshowstarts a new figure.draw(x, y, label)— Append the point (x, y) to the curve calledlabel.show(final=True)— Redraw all curves; the book build renders only the final call. 27.9절
class RNN(d2l.Module)
RNN(num_inputs, num_hiddens, sigma=0.01)The RNN model implemented with high-level APIs. 8.4.6절
call(inputs, H=None, training=None)forward(inputs, H=None)
class RNNLM(d2l.RNNLMScratch)
The RNN-based language model implemented with high-level APIs. 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. ?sec-word2vec-data
draw()
class ResNeXtBlock(tf.keras.Model)
ResNeXtBlock(num_channels, groups, bot_mul, use_1x1conv=False, strides=1)The ResNeXt block. 7.4절
call(X)
class Residual(tf.keras.Model)
Residual(num_channels, use_1x1conv=False, strides=1)The Residual block of ResNet models. 7.4절
call(X)
class SGD(d2l.HyperParameters)
SGD(lr)Minibatch stochastic gradient descent. 2.4절
apply_gradients(grads_and_vars)
class SNLIDataset
SNLIDataset(dataset, num_steps, vocab=None)A customized dataset to load the SNLI dataset. ?sec-natural-language-inference-and-dataset
class SoftmaxRegression(d2l.Classifier)
SoftmaxRegression(num_outputs, lr)The softmax regression model. 3.3.5절
forward(X)
class SyntheticRegressionData(d2l.DataModule)
SyntheticRegressionData(w, b, noise=0.01, num_train=1000, num_val=1000, batch_size=32)Synthetic data for linear regression. 2.4절
get_dataloader(train)
class TimeMachine(d2l.DataModule)
TimeMachine(batch_size, num_steps, num_train=50000, num_val=5000, tokenization='bpe', vocab_size=1024)The Time Machine dataset. 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 TokenEmbedding
TokenEmbedding(embedding_name)Token Embedding. ?sec-synonyms
class Tracker(d2l.Trainer)
Tracker(max_epochs, datasets)A Trainer that records the accuracy on named datasets every epoch. 4.5절
validate()
class TrainCallback(tf.keras.callbacks.Callback)
TrainCallback(net, train_iter, test_iter, num_epochs, device_name)A callback to visualize the training progress. 27.9절
on_epoch_begin(epoch, logs=None)on_epoch_end(epoch, logs)
class Trainer(d2l.HyperParameters)
Trainer(max_epochs, num_gpus=0, gradient_clip_val=0)Fit a Module to a DataModule, keeping a per-epoch history. 2.4절
prepare_data(data)prepare_optimizer(model)fit(model, data)record(split, metrics, x)prepare_model(model)train_step(batch)val_step(batch)fit_epoch()validate()evaluate(model, data, train=False)— Metrics ofmodelon the validation data ofdata(on its training 3.3절prepare_batch(batch)clip_gradients(grad_clip_val, grads)
class VOCSegDataset
VOCSegDataset(is_train, crop_size, voc_dir)A customized dataset to load the VOC dataset. ?sec-semantic-segmentation
normalize_image(img)filter(imgs)
class Vocab
Vocab(tokens=(), min_freq=0, reserved_tokens=())Vocabulary for text. 8.2절
to_tokens(indices)unk()
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, value=None)— V(s) for a batch of states;valueplays the part ofpolicyvalue_np(obs)— V(s) for a numpy batch of states, as numpy, through a forwardtabular(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 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 ArrayDataLoader(d2l.ArrayLoader)
ArrayDataLoader(*args, batch_size=32, shuffle=False, drop_last=False)d2l.ArrayLoader that yields JAX arrays and also accepts a dataset. 27.9절
class ArrayLoader
ArrayLoader(arrays, batch_size, shuffle=False, drop_last=False, key=None)Minibatches of in-memory arrays, reshuffled each pass if shuffle. 2.4절
class AttentionMixer(d2l.CausalAttention)
AttentionMixer(num_hiddens, num_heads, conv_width=None, rope=True, rngs)Causal multi-head attention, with rotary positions unless rope is 12.1.4절
qkv(X, offset=0, tables=None)
class Autoencoder(nnx.Module)
Autoencoder(latent_channels=4, ch=64, num_blocks=2, rngs)Residual convolutional autoencoder from 28x28x1 images to a 7x7 17.7절
encode(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(nnx.Module)
BERTEncoder(vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout, max_len=1000, rngs=None)BERT encoder. ?sec-bert
class BERTModel(nnx.Module)
BERTModel(vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout, max_len=1000, rngs=None)The BERT model. ?sec-bert
class BPETokenizer
BPETokenizer(vocab_size=1024, pattern=None, specials=('<pad>', '<bos>', '<eos>'))Byte-level BPE tokenizer trained by iterated most-frequent-pair 8.2절
class BananasDataset
BananasDataset(is_train)A customized dataset to load the banana detection dataset. ?sec-object-detection-dataset
class Batch
Batch(obs, act, rew, next_obs, term, ep_ends)A flat batch of transitions, plus the episode boundaries. 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')Time a callable: warmup, then device-synchronized average seconds. 5.7절
class CausalAttention(nnx.Module)
CausalAttention(num_hiddens, num_heads, bias=False, rope=False, num_kv_heads=None, rngs)Causal self-attention, optionally rotary; num_kv_heads < num_heads 11.2절
qkv(X, offset=0, tables=None)— Queries, keys, and values of X, each (batch, heads, length, headattend(q, k, v)— Causal attention of (batch, length, heads, head width) queries,
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 Conv(nnx.Conv)
Conv(in_features, out_features, kernel_size, rngs, **kwargs)nnx.Conv (kernel_size a tuple), all weights from U(+-1/sqrt(fan_in)). 17.4절
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(nnx.Module)
DiT(img_size=28, patch_size=4, num_channels=1, width=256, depth=6, num_heads=4, num_classes=None, rngs)Diffusion transformer (NHWC) conditioned on a time t in [0, 1] and, 17.7절
class DiTBlock(d2l.ViTBlock)
DiTBlock(num_hiddens, mlp_num_hiddens, num_heads, rngs)ViTBlock with adaLN-Zero: the condition c sets a shift, a scale and a 17.7절
class Discriminator(nnx.Module)
Discriminator(resolution, base_ch, rngs)Critic that mirrors the generator: conv + leaky ReLU + bilinear 16.5절
phi(x)
class DotProductAttention(nnx.Module)
DotProductAttention(dropout=0.0, rngs=None)Scaled dot-product attention over the last two axes. 10.2절
attention_weights()— Weights of the last eager call: (…, queries, keys).
class EMA
EMA(model, half_life)Exponential moving average of a model’s parameters, given as a 16.5절
update(model)average(avg, model, decay)— Move the parameters of avg toward those of model, in place.
class Embed(nnx.Embed)
nnx.Embed whose gradient is a matrix product for small vocabularies. 27.9절
class FashionCNN(nnx.Module)
FashionCNN(rngs)A compact CNN for Fashion-MNIST: two conv-pool stages, two linear. 9.5절
class FashionMNIST(d2l.DataModule)
FashionMNIST(batch_size=64, resize=(28, 28))The Fashion-MNIST dataset. 3.2절
class FeatureCNN(nnx.Module)
FeatureCNN(feature_dim=128, resolution=32, rngs=None)Three conv blocks, global average pooling, and a linear head. Inputs 27.9절
features(x)
class FeedForward(nnx.Module)
FeedForward(num_hiddens, act='swiglu', bias=False, rngs)Position-wise FFN: GELU MLP or SwiGLU at matched parameter count. 11.1절
class GPT(nnx.Module)
GPT(vocab_size, num_hiddens=256, num_heads=8, num_blks=6, max_len=1024, pos='rope', norm='rms', act='swiglu', pre_norm=True, bias=False, dropout=0, num_kv_heads=None, ffn_factory=None, rngs)Decoder-only transformer language model built from configurable 11.2절
class GatedDeltaNet(d2l.GatedLinearAttention)
GatedDeltaNet(num_hiddens, num_heads, chunk_size=32, conv_width=4, timescales=(4, 256), rngs)Gated linear attention whose memory is written by the delta rule. 12.7절
memory(X, Q, K, V, log_a)
class GatedLinearAttention(nnx.Module)
GatedLinearAttention(num_hiddens, num_heads, chunk_size=16, conv_width=4, timescales=(4, 256), rngs)Multi-head linear attention with one input-dependent decay per head. 12.6절
class GaussianHead(nnx.Module)
GaussianHead(obs_dim, act_dim, hidden, state_std=False, trunk=None, zero_mean=False, rngs)A Gaussian over actions: a trunk of hidden features, a linear mean, 14.9절
class GaussianMixture
GaussianMixture(means, weights, std)A mixture of isotropic Gaussians, exact at every noise level. 17.1절
three_modes()— The chapter’s running example, with mode weights 0.5/0.3/0.2.sample(key, n)— n draws from the mixture.log_prob(x, alpha=1.0, sigma=0.0)— log p(x) for x = alpha x0 + sigma eps.score(x, alpha=1.0, sigma=0.0)— The gradient of log p(x) for x = alpha x0 + sigma eps.posterior_mean(x, alpha, sigma)— E[x0 | x]; finite at alpha = 0 and at sigma = 0.nll(x)— Mean negative log-likelihood of clean points, in nats. 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)— Arrays 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 predictionoutof 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, policy=None)— log pi(a|s): the Normal density, summed over action dimensions.act(obs, rng)— Sample mu(s) + sigma(s) z, z ~ N(0, I) from the numpy rng.act_greedy(obs, rng=None)— The mean action mu(s).
class Generator(nnx.Module)
Generator(latent_dim, resolution, base_ch, extra_ch=0, const_ch=128, rngs)Learned 4x4 constant + projected latent (+ extra 4x4 input maps), 16.5절
class HyperParameters
The base class of hyperparameters. 27.9절
save_hyperparameters(ignore=None)— Save function arguments into instance attributes. 27.9절
class LMOptimizer(nnx.Optimizer)
LMOptimizer(model, lr, num_steps, warmup, weight_decay=0.1, max_norm=1.0)AdamW with weight decay on the weight matrices only, a linear warmup 11.2절
class LeNet(d2l.Classifier)
LeNet(lr=0.1, num_classes=10, kernel_init=None, rngs=None)The layout of LeNet-5, with sigmoid activations and average pooling. 6.6절
class Linear(nnx.Linear)
Linear(in_features, out_features, use_bias=True, rngs, **kwargs)nnx.Linear with weights and biases drawn from U(-a, a), where 10.3절
class LinearRegression(d2l.Module)
LinearRegression(num_inputs, lr, rngs=None)Linear regression built from framework components. 2.5절
loss(y_hat, y)configure_optimizers()get_w_b()
class LinearRegressionScratch(d2l.Module)
LinearRegressionScratch(num_inputs, lr, sigma=0.01, rngs=None)The linear regression model implemented from scratch. 2.4절
forward(X)loss(y_hat, y)configure_optimizers()
class Mamba(nnx.Module)
Mamba(num_hiddens, num_states=16, expand=2, conv_width=4, rngs, **ssm_args)The Mamba layer: a gated selective SSM between two projections. 12.5절
ssm_input(X)— The input of the SSM and the gate branch.
class MaskLM(nnx.Module)
MaskLM(vocab_size, num_hiddens, rngs=None)The masked language model task of BERT. ?sec-bert
class MinGRU(nnx.Module)
MinGRU(num_inputs, num_hiddens, rngs)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.
class MixtureGenerator(nnx.Module)
MixtureGenerator(mu, A)x = mu_k + z A_k for a uniformly drawn component k. 16.2절
params_np()
class Module(nnx.Module, d2l.HyperParameters)
The base class of models. 2.4절
loss(y_hat, y)forward(X, *args, **kwargs)training_step(batch)— The mean loss on one minibatch, or a dict of batch-mean metricsvalidation_step(batch)— The mean loss on one minibatch of validation data, or a dict ofconfigure_optimizers()
class MultiHeadAttention(nnx.Module)
MultiHeadAttention(num_hiddens, num_heads, dropout=0.0, bias=False, num_kv_heads=None, rngs)Multi-head attention with heads as an explicit axis; num_kv_heads < 10.3절
class NextSentencePred(nnx.Module)
NextSentencePred(num_hiddens, rngs=None)The next sentence prediction task of BERT. ?sec-bert
class PatchEmbedding(nnx.Module)
PatchEmbedding(img_size=96, patch_size=16, num_hiddens=512, num_channels=3, rngs)Image-to-sequence stem of the vision transformer. 11.5절
class Policy(nnx.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, policy=None)— log pi(a|s). Gradients flow w.r.t. the module you differentiate;tabular(num_states, num_actions, lr=0.1, seed=None)— One preference theta_{s,a} per state-action pair: an embedding.act(obs, rng)— Sample an action; numpy in, int out, the acting protocol of evaluate. 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. The 14.5절probs(num_states, num_actions)— pi(a|s) for every pair, as a (num_states, num_actions) numpy array. 14.5절
class ProgressBoard(d2l.HyperParameters)
ProgressBoard(xlabel=None, ylabel=None, xlim=None, ylim=None, xscale='linear', yscale='linear', figsize=(3.5, 2.5), display=True)Curves that grow during training; show redraws them. 2.4절
clear()— Forget all curves; the nextshowstarts a new figure.draw(x, y, label)— Append the point (x, y) to the curve calledlabel.show(final=True)— Redraw all curves; the book build renders only the final call. 27.9절
class RNN(nnx.Module)
RNN(num_inputs, num_hiddens, sigma=0.01, rngs=None)The RNN model implemented with high-level APIs. 8.4.6절
class RNNLM(d2l.RNNLMScratch)
RNNLM(rnn, vocab_size, lr=0.01, dropout=0, emb_dropout=0, rngs=None)The RNN-based language model implemented with high-level APIs. 8.4.6절
embedding(X)output_layer(hiddens)
class RNNLMScratch(d2l.Classifier)
RNNLMScratch(rnn, vocab_size, lr=0.01, dropout=0, emb_dropout=0, rngs=None)The RNN-based language model implemented from scratch. 8.4.2절
validation_step(batch)embedding(X)output_layer(rnn_outputs)forward(X, state=None)predict(prefix, num_tokens, tok, device=None, temperature=0.0)
class RNNScratch(nnx.Module)
RNNScratch(num_inputs, num_hiddens, sigma=0.01, rngs=None)The RNN model implemented from scratch. 8.4.2절
class RandomGenerator
RandomGenerator(sampling_weights)Randomly draw among {1, …, n} according to n sampling weights. ?sec-word2vec-data
draw()
class RecallModel(nnx.Module)
RecallModel(layer, num_hiddens, vocab_size=16, num_inputs=32, num_outputs=8, rngs)Embedding, a sequence layer, and a classifier at every position. 12.1.4절
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 ResNeXtBlock(nnx.Module)
ResNeXtBlock(num_channels, groups, bot_mul, use_1x1conv=False, strides=(1, 1), in_channels=None, rngs=None)The ResNeXt block. 7.4절
class Residual(nnx.Module)
Residual(num_channels, use_1x1conv=False, strides=(1, 1), in_channels=None, rngs=None)The Residual block of ResNet models. 7.4절
class S4D(nnx.Module)
S4D(num_hiddens, num_states=16, dt_min=0.001, dt_max=0.1, rngs)A diagonal state space layer: N states per channel, fixed dynamics. 12.4절
discretize()— Zero-order hold with B = 1: decays a_bar and input weights b_bar.step(x, h)— One step: x is (batch_size, d); the state h is (batch_size, d, N). 12.4절
class SGD(d2l.HyperParameters)
SGD(lr)Minibatch stochastic gradient descent. 2.4절
init(params)update(updates, state, params=None)
class SNLIDataset
SNLIDataset(dataset, num_steps, vocab=None)A customized dataset to load the SNLI dataset. ?sec-natural-language-inference-and-dataset
class SelectiveSSM(nnx.Module)
SelectiveSSM(num_channels, dt_rank, num_states=16, dt_min=0.001, dt_max=0.1, selective=True, rngs)A diagonal SSM with N states for each of num_channels channels. Its 12.5절
log_coefficients(U)— Log-decays and writes, each of shape (batch_size, T, H, N). 12.5절
class SeqLM(nnx.Module)
SeqLM(vocab_size, num_hiddens, mixers, rngs)A language model of residual blocks: a sequence mixer, then an MLP. 12.1.4절
first_mixer_input(X)— What the first mixer reads: the normalized token embeddings. 12.3절
class Shift(nnx.Module)
Shift(theta0)The generator x’ = theta + z. 16.2절
class SoftmaxRegression(d2l.Classifier)
SoftmaxRegression(num_outputs, lr, num_inputs=784, rngs=None)The softmax regression model. 3.3.5절
forward(X)
class SquashedGaussianPolicy(nnx.Module)
SquashedGaussianPolicy(obs_dim, act_dim, hidden=64, scale=2.0, seed=None)d2l.GaussianHead with SAC’s network (two ReLU layers and a 15.5절
log_prob_u(u, mean, std)— log pi at a = scale tanh(u), from the pre-squash u the samplersample(obs, key)— A reparameterized action and its log-probability, differentiable.act(obs, rng)— A sampled action, numpy in and out.act_logp(obs, rng)— A sampled action and its log-probability, numpy in and out.act_greedy(obs, rng=None)— The squashed mean scale * tanh(mean), numpy in and out.
class SyntheticRegressionData(d2l.DataModule)
SyntheticRegressionData(w, b, noise=0.01, num_train=1000, num_val=1000, batch_size=32, key=None)Synthetic data for linear regression. 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절
class TensorFlowDataLoader
TensorFlowDataLoader(dataset)Expose a tf.data.Dataset as re-iterable NumPy batches. 3.2절
class TimeMLP(nnx.Module)
TimeMLP(hidden=256, depth=3, dim=2, num_times=1, time_dim=64, time_freqs=(1.0, 64.0), rngs)An MLP on a point x and the time features of one or more times; 17.1절
class TimeMachine(d2l.DataModule)
TimeMachine(batch_size, num_steps, num_train=50000, num_val=5000, tokenization='bpe', vocab_size=1024)The Time Machine dataset. 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(nnx.Module)
TinyCharLM(vocab_size, num_hiddens=128, num_heads=4, num_blks=2, pos='rope', max_len=512, bias=False, rngs)Attention-only language model. 10.4절
stream(X, num_blks=None)— Residual stream after the first num_blks blocks (default: all),attention_weights(X)— Per-block attention maps, each (batch, num_heads, T, T).embed(X)— Token embeddings plus the absolute position code, if any. 10.4절alibi(T)— 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(nnx.Module)
TinyLM(vocab_size, d_model=128, num_heads=2, num_blks=2, max_len=64, rngs)A small decoder-only transformer language model. 9.5절
attention(blk, X)
class TokenEmbedding
TokenEmbedding(embedding_name)Token Embedding. ?sec-synonyms
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_model(model)fit(model, data)record(split, metrics, x)fit_epoch()validate()evaluate(model, data, train=False)— Metrics ofmodelon the validation data ofdata(on its training 3.3절prepare_batch(batch)prepare_optimizer(model)
class TransformerBlock(nnx.Module)
TransformerBlock(num_hiddens, num_heads, dropout=0, norm='rms', act='swiglu', pre_norm=True, bias=False, attn_factory=None, ffn_factory=None, rngs)Configurable transformer block: attention + FFN on a residual 11.1절
class UNet(nnx.Module)
UNet(ch=64, num_classes=None, in_channels=1, out_channels=1, emb_dim=128, time_freqs=(1.0, 64.0), rngs)A small U-Net on an image x (n, h, w, c), times t (n,) and labels y. 17.4절
class UNetBlock(nnx.Module)
UNetBlock(c_in, c_out, emb_dim=None, rngs)Two 3x3 convolutions with group norm, a residual, and an embedding. 17.4절
class UNetFlowMap(nnx.Module)
UNetFlowMap(unet, rngs)u(x, s, t): a velocity U-Net, plus a zero-initialized input for the 17.8절
class VOCSegDataset
VOCSegDataset(is_train, crop_size, voc_dir)A customized dataset to load the VOC dataset. ?sec-semantic-segmentation
normalize_image(img)filter(imgs)
class VerifierTask
Four prompts, nine candidate responses shared by all of them, an 14.1절
verify(x, y)— The verifier: reward 1 iff response y is prompt x’s answer.reward_table(reward)— reward(x, y) for every prompt x (rows) and response y (columns).policy(theta)— pi(y | x): a softmax over each prompt’s row of preferences.success(pi, reward=None)— E r(x, y), y ~ pi(. | x), averaged over the prompts; r = verify
class ViT(d2l.Classifier)
ViT(img_size, patch_size, num_hiddens, mlp_num_hiddens, num_heads, num_blks, num_steps, emb_dropout=0.0, blk_dropout=0.0, lr=0.001, use_bias=False, num_classes=10, num_channels=1, rngs)Vision transformer. 11.5절
forward(X)configure_optimizers()
class ViTBlock(d2l.TransformerBlock)
ViTBlock(num_hiddens, mlp_num_hiddens, num_heads, dropout, use_bias=False, rngs)Pre-norm block with LayerNorm and an exact-GELU MLP. 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 atstarts.train_dataloader()val_dataloader()
class Accumulator
Accumulator(n)For accumulating sums over n variables. 27.9절
add(*args)reset()
class Animator
Animator(xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1, figsize=(3.5, 2.5))For plotting data in animation. 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 ArrayLoader
ArrayLoader(arrays, batch_size, shuffle=False, drop_last=False)Minibatches of in-memory arrays, reshuffled each pass if shuffle. 2.4절
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.Block)
BERTEncoder(vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout, max_len=1000)BERT encoder. ?sec-bert
forward(tokens, segments, valid_lens)
class BERTModel(nn.Block)
BERTModel(vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_blks, dropout, max_len=1000)The BERT model. ?sec-bert
forward(tokens, segments, valid_lens=None, pred_positions=None)
class BPETokenizer
BPETokenizer(vocab_size=1024, pattern=None, specials=('<pad>', '<bos>', '<eos>'))Byte-level BPE tokenizer trained by iterated most-frequent-pair 8.2절
class BananasDataset(gluon.data.Dataset)
BananasDataset(is_train)A customized dataset to load the banana detection dataset. ?sec-object-detection-dataset
class Benchmark
Benchmark(f, warmup=3, repeats=10, desc='time')Time a callable: warmup, then device-synchronized average seconds. 5.7절
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 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 FashionMNIST(d2l.DataModule)
FashionMNIST(batch_size=64, resize=(28, 28))The Fashion-MNIST dataset. 3.2절
read(train)— Images and labels of one split, read from the published files.to_dataset(images, labels)— Convert all images at once: channel axis first, values in [0, 1].text_labels(indices)— Return text labels. 3.2절get_dataloader(train)batchify(examples)— Stack examples into a minibatch and resize it if asked to. 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 HyperParameters
The base class of hyperparameters. 27.9절
save_hyperparameters(ignore=None)— Save function arguments into instance attributes. 27.9절
class LeNet(d2l.Classifier)
LeNet(lr=0.1, num_classes=10)The layout of LeNet-5, with sigmoid activations and average pooling. 6.6절
class LinearRegression(d2l.Module)
LinearRegression(lr)Linear regression built from framework components. 2.5절
loss(y_hat, y)configure_optimizers()get_w_b()
class LinearRegressionScratch(d2l.Module)
LinearRegressionScratch(num_inputs, lr, sigma=0.01)The linear regression model implemented from scratch. 2.4절
forward(X)loss(y_hat, y)configure_optimizers()
class MaskLM(nn.Block)
MaskLM(vocab_size, num_hiddens)The masked language model task of BERT. ?sec-bert
forward(X, pred_positions)
class MaskedSoftmaxCELoss(gluon.loss.SoftmaxCELoss)
The softmax cross-entropy loss with masks. 27.9절
forward(pred, label, valid_len)
class Module(nn.Block, 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 metricsvalidation_step(batch)— The mean loss on one minibatch of validation data, or a dict ofconfigure_optimizers()
class NextSentencePred(nn.Block)
The next sentence prediction task of BERT. ?sec-bert
forward(X)
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 nextshowstarts a new figure.draw(x, y, label)— Append the point (x, y) to the curve calledlabel.show(final=True)— Redraw all curves; the book build renders only the final call. 27.9절
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. ?sec-word2vec-data
draw()
class ResNeXtBlock(nn.HybridBlock)
ResNeXtBlock(num_channels, groups, bot_mul, use_1x1conv=False, strides=1)The ResNeXt block. 7.4절
forward(X)
class Residual(nn.HybridBlock)
Residual(num_channels, use_1x1conv=False, strides=1)The Residual block of ResNet models. 7.4절
forward(X)
class SGD(d2l.HyperParameters)
SGD(params, lr)Minibatch stochastic gradient descent. 2.4절
step(_)
class SNLIDataset(gluon.data.Dataset)
SNLIDataset(dataset, num_steps, vocab=None)A customized dataset to load the SNLI dataset. ?sec-natural-language-inference-and-dataset
class SoftmaxRegression(d2l.Classifier)
SoftmaxRegression(num_outputs, lr)The softmax regression model. 3.3.5절
forward(X)
class SyntheticRegressionData(d2l.DataModule)
SyntheticRegressionData(w, b, noise=0.01, num_train=1000, num_val=1000, batch_size=32)Synthetic data for linear regression. 2.4절
get_dataloader(train)
class TimeMachine(d2l.DataModule)
TimeMachine(batch_size, num_steps, num_train=50000, num_val=5000, tokenization='bpe', vocab_size=1024)The Time Machine dataset. 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 TokenEmbedding
TokenEmbedding(embedding_name)Token Embedding. ?sec-synonyms
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)fit(model, data)record(split, metrics, x)fit_epoch()validate()evaluate(model, data, train=False)— Metrics ofmodelon the validation data ofdata(on its training 3.3절prepare_batch(batch)prepare_model(model)clip_gradients(grad_clip_val, model)
class VOCSegDataset(gluon.data.Dataset)
VOCSegDataset(is_train, crop_size, voc_dir)A customized dataset to load the VOC dataset. ?sec-semantic-segmentation
normalize_image(img)filter(imgs)
class Vocab
Vocab(tokens=(), min_freq=0, reserved_tokens=())Vocabulary for text. 8.2절
to_tokens(indices)unk()
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. ?sec-anchor
associative_recall
associative_recall(rng, batch_size, num_pairs, num_keys=512, num_values=4, num_steps=256, num_rebound=0, gap=None)Key-value pairs, filler, then every key again as a query. The first 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. ?sec-word2vec-data
bbox_to_rect
bbox_to_rect(bbox, color)Convert bounding box to matplotlib format. ?sec-bbox
beam_search
beam_search(step_fn, prefix, num_tokens, beam_size=4, alpha=0.75, eos_id=None)Length-normalized beam search (score = log P / len^alpha). 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). ?sec-bbox
box_corner_to_center
box_corner_to_center(boxes)Convert from (upper-left, lower-right) to (center, width, height). ?sec-bbox
box_iou
box_iou(boxes1, boxes2)Compute pairwise IoU across two lists of anchor or bounding boxes. ?sec-anchor
bpb_from_nll
bpb_from_nll(sum_nll_nats, n_bytes)Bits per byte from a summed negative log-likelihood in nats and the
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)
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. ?sec-kaggle-cifar10
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. ?sec-word2vec-data
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. ?sec-word2vec-data
get_tokens_and_segments
get_tokens_and_segments(tokens_a, tokens_b=None)Get tokens of the BERT input sequence and their segment IDs. ?sec-bert
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. ?sec-object-detection-dataset
load_data_fashion_mnist
load_data_fashion_mnist(batch_size, resize=None)Download the Fashion-MNIST dataset and then load it into memory. 27.9절
load_data_imdb
load_data_imdb(batch_size, num_steps=500)Return data iterators and the vocabulary of the IMDb review dataset. ?sec-sentiment
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. ?sec-word2vec-data
load_data_snli
load_data_snli(batch_size, num_steps=50)Download the SNLI dataset and return data iterators and vocabulary. ?sec-natural-language-inference-and-dataset
load_data_voc
load_data_voc(batch_size, crop_size)Load the VOC semantic segmentation dataset. ?sec-semantic-segmentation
load_data_wiki
load_data_wiki(batch_size, max_len)Load the WikiText-2 dataset. ?sec-bert-dataset
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. ?sec-anchor
multibox_prior
multibox_prior(data, sizes, ratios)Generate anchor boxes with different shapes centered on each pixel. ?sec-anchor
multibox_target
multibox_target(anchors, labels)Label anchor boxes using ground-truth bounding boxes. ?sec-anchor
naive_blocks
naive_blocks(page)The text blocks of a page, split at block-level tags, as (text,
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. ?sec-anchor
no_duplicate_batches
no_duplicate_batches(queries, passages, batch_size, seed=0, negatives=None)Batches of indices into the pairs (queries[i], passages[i]), in a
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. ?sec-anchor
offset_inverse
offset_inverse(anchors, offset_preds)Predict bounding boxes based on anchor boxes with predicted offsets. ?sec-anchor
on_grid
on_grid(runs, grid, col, smooth=1)Resample per-episode rows (env step, value, …) onto an env-step 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절
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. ?sec-sentiment-rnn
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. ?sec-natural-language-inference-attention
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
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. ?sec-kaggle-cifar10
read_data_bananas
read_data_bananas(is_train=True)Read the banana detection dataset images and labels. ?sec-object-detection-dataset
read_data_nmt
read_data_nmt()Load the English-French dataset. 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. ?sec-sentiment
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. ?sec-word2vec-data
read_snli
read_snli(data_dir, is_train)Read the SNLI dataset into premises, hypotheses, and labels. ?sec-natural-language-inference-and-dataset
read_voc_images
read_voc_images(voc_dir, is_train=True)Read all VOC feature and label images. ?sec-semantic-segmentation
rebuild_c0
rebuild_c0(manifest='lm-c0-docs-v1', warc_path=None, cache_dir=None, workers=None)Rebuild the c0 documents from their manifest rows (a DATA_HUB key or
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. ?sec-kaggle-cifar10
reorg_train_valid
reorg_train_valid(data_dir, labels, valid_ratio)Split the validation set out of the original training set. ?sec-kaggle-cifar10
repeated_spans
repeated_spans(ids, sa, lcp, min_len)The maximal repeats of at least min_len tokens, as (start, length,
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. ?sec-anchor
show_gray
show_gray(imgs, num_rows, num_cols, titles=None, scale=1.0)Show images (n, 1, h, w) in [-1, 1], or binary (n, h, w), in gray. 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. ?sec-word2vec-data
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). ?sec-image-augmentation
train_ch13
train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices=d2l.try_all_gpus())Train a model with multiple GPUs (defined in Chapter 13). ?sec-image-augmentation
train_ch6
train_ch6(net, train_iter, test_iter, num_epochs, lr, device)Train a model with a GPU (defined in Chapter 6). 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. ?sec-semantic-segmentation
voc_label_indices
voc_label_indices(colormap, colormap2label)Map any RGB values in VOC labels to their class indices. ?sec-semantic-segmentation
voc_rand_crop
voc_rand_crop(feature, label, height, width)Randomly crop both feature and label images. ?sec-semantic-segmentation
warc_record_at
warc_record_at(path, offset, length)The WarcRecord stored in bytes offset..offset+length-1 of a local
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|
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절
as_metrics
as_metrics(out)A step returns a loss or a dict of metrics; return a dict. 2.4절
assign_anchor_to_bbox
assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5)Assign closest ground-truth bounding boxes to anchor boxes. ?sec-anchor
batchify
batchify(data)Return a minibatch of examples for skip-gram with negative sampling. ?sec-word2vec-data
bbox_to_rect
bbox_to_rect(bbox, color)Convert bounding box to matplotlib format. ?sec-bbox
beam_search
beam_search(step_fn, prefix, num_tokens, beam_size=4, alpha=0.75, eos_id=None)Length-normalized beam search (score = log P / len^alpha). 8.6.3절
box_center_to_corner
box_center_to_corner(boxes)Convert from (center, width, height) to (upper-left, lower-right). ?sec-bbox
box_corner_to_center
box_corner_to_center(boxes)Convert from (upper-left, lower-right) to (center, width, height). ?sec-bbox
box_iou
box_iou(boxes1, boxes2)Compute pairwise IoU across two lists of anchor or bounding boxes. ?sec-anchor
build_array_nmt
build_array_nmt(lines, vocab, num_steps)Transform text sequences of machine translation into minibatches. 27.9절
check_shape
check_shape(a, shape)Check the shape of a tensor. 8.4.2절
copyfile
copyfile(filename, target_dir)Copy a file into a target directory. ?sec-kaggle-cifar10
corr2d
corr2d(X, K)Compute 2D cross-correlation. 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절
cpu
cpu()Get the CPU device. 5.7절
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절
drop_path
drop_path(Y, p, training)Zero each example of Y with probability p, rescale the rest. 7.6절
evaluate_accuracy
evaluate_accuracy(net, data_iter)Compute the accuracy for a model on a dataset. 27.9절
evaluate_loss
evaluate_loss(net, data_iter, loss)Evaluate the loss of a model on the given dataset. 27.9절
extract
extract(filename, folder=None)Extract a zip/tar file into folder. 27.9절
get_centers_and_contexts
get_centers_and_contexts(corpus, max_window_size)Return center words and context words in skip-gram. ?sec-word2vec-data
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. ?sec-word2vec-data
get_tokens_and_segments
get_tokens_and_segments(tokens_a, tokens_b=None)Get tokens of the BERT input sequence and their segment IDs. ?sec-bert
gpu
gpu(i=0)Get a GPU device. 5.7절
grad_clipping
grad_clipping(grads, theta)Clip the gradient. 27.9절
kneser_ney
kneser_ney(train, tokens, vocab_size, n=3)Interpolated Kneser-Ney log-probabilities (nats) of each of tokens. 8.3절
linreg
linreg(X, w, b)The linear regression model. 27.9절
load_array
load_array(data_arrays, batch_size, is_train=True)Construct a TensorFlow data iterator. 27.9절
load_data_bananas
load_data_bananas(batch_size)Load the banana detection dataset. ?sec-object-detection-dataset
load_data_fashion_mnist
load_data_fashion_mnist(batch_size, resize=None)Download the Fashion-MNIST dataset and then load it into memory. 27.9절
load_data_imdb
load_data_imdb(batch_size, num_steps=500)Return data iterators and the vocabulary of the IMDb review dataset. ?sec-sentiment
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. ?sec-word2vec-data
load_data_snli
load_data_snli(batch_size, num_steps=50)Download the SNLI dataset and return data iterators and vocabulary. ?sec-natural-language-inference-and-dataset
load_data_voc
load_data_voc(batch_size, crop_size)Load the VOC semantic segmentation dataset. ?sec-semantic-segmentation
load_data_wiki
load_data_wiki(batch_size, max_len)Load the WikiText-2 dataset. ?sec-bert-dataset
mixup
mixup(X, y, alpha)Mix a minibatch with a shuffled copy; return both label sets. 7.6절
multibox_detection
multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5, pos_threshold=0.009999999)Predict bounding boxes using non-maximum suppression. ?sec-anchor
multibox_prior
multibox_prior(data, sizes, ratios)Generate anchor boxes with different shapes centered on each pixel. ?sec-anchor
multibox_target
multibox_target(anchors, labels)Label anchor boxes using ground-truth bounding boxes. ?sec-anchor
nms
nms(boxes, scores, iou_threshold)Sort confidence scores of predicted bounding boxes. ?sec-anchor
num_gpus
num_gpus()Get the number of available GPUs. 5.7절
num_params
num_params(model)The number of trainable parameters. 7.5.1.1절
offset_boxes
offset_boxes(anchors, assigned_bb, eps=1e-06)Transform for anchor box offsets. ?sec-anchor
offset_inverse
offset_inverse(anchors, offset_preds)Predict bounding boxes based on anchor boxes with predicted offsets. ?sec-anchor
plot
plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None, legend_loc=None)Plot data points. 27.9절
predict_sentiment
predict_sentiment(net, vocab, sequence)Predict the sentiment of a text sequence. ?sec-sentiment-rnn
predict_seq2seq
predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps, 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. ?sec-natural-language-inference-attention
preprocess_nmt
preprocess_nmt(text)Preprocess the English-French dataset. 27.9절
print_wrapped
print_wrapped(*args, width=76)Print like print, folding each line to the width of a page. 8.2절
read_csv_labels
read_csv_labels(fname)Read fname to return a filename to label dictionary. ?sec-kaggle-cifar10
read_data_bananas
read_data_bananas(is_train=True)Read the banana detection dataset images and labels. ?sec-object-detection-dataset
read_data_nmt
read_data_nmt()Load the English-French dataset. 27.9절
read_imdb
read_imdb(data_dir, is_train)Read the IMDb review dataset text sequences and labels. ?sec-sentiment
read_ptb
read_ptb()Load the PTB dataset into a list of text lines. ?sec-word2vec-data
read_snli
read_snli(data_dir, is_train)Read the SNLI dataset into premises, hypotheses, and labels. ?sec-natural-language-inference-and-dataset
read_voc_images
read_voc_images(voc_dir, is_train=True)Read all VOC feature and label images. ?sec-semantic-segmentation
reorg_test
reorg_test(data_dir)Organize the testing set for data loading during prediction. ?sec-kaggle-cifar10
reorg_train_valid
reorg_train_valid(data_dir, labels, valid_ratio)Split the validation set out of the original training set. ?sec-kaggle-cifar10
resnet18
resnet18(num_classes, in_channels=1)A slightly modified ResNet-18 model built with Keras. 13.6절
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, grads, lr, batch_size)Minibatch stochastic gradient descent. 27.9절
show_bboxes
show_bboxes(axes, bboxes, labels=None, colors=None)Show bounding boxes. ?sec-anchor
show_heatmaps
show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5), cmap='Reds', cbar=True, xticklabels=None, yticklabels=None)Show heatmaps of matrices; cbar is True (shared), ‘each’ or False. 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절
split_batch
split_batch(X, y, devices)Split X and y into multiple devices. 13.5절
squared_loss
squared_loss(y_hat, y)Squared loss. 27.9절
subsample
subsample(sentences, vocab)Subsample high-frequency words. ?sec-word2vec-data
synthetic_data
synthetic_data(w, b, noise, n)n examples with standard normal features and labels Xw + b + noise. 2.2절
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절
train_batch_ch13
train_batch_ch13(net, X, y, loss, optimizer)Train for a minibatch with Keras (defined in Chapter 13). ?sec-image-augmentation
train_ch13
train_ch13(net, train_iter, test_iter, loss, optimizer, num_epochs)Train a model with Keras (defined in Chapter 13). ?sec-image-augmentation
train_ch6
train_ch6(net_fn, train_iter, test_iter, num_epochs, lr, device)Train a model with a GPU (defined in Chapter 6). 27.9절
train_seq2seq
train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device)Train a model for sequence to sequence. 27.9절
truncate_pad
truncate_pad(line, num_steps, padding_token)Truncate or pad sequences. 27.9절
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절
use_svg_display
use_svg_display()Use the svg format to display a plot in Jupyter. 27.9절
voc_colormap2label
voc_colormap2label()Build the mapping from RGB to class indices for VOC labels. ?sec-semantic-segmentation
voc_label_indices
voc_label_indices(colormap, colormap2label)Map any RGB values in VOC labels to their class indices. ?sec-semantic-segmentation
voc_rand_crop
voc_rand_crop(feature, label, height, width)Randomly crop both feature and label images. ?sec-semantic-segmentation
add_to_class
add_to_class(Class)Register functions as methods in created class. 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절
allreduce_megabytes
allreduce_megabytes(compiled)Megabytes of fp32 results of each allreduce in a compiled program, 13.6절
ancestral_sample
ancestral_sample(pred, x, path, steps, key, t_start=1.0)Ho et al.’s sampler from x at t_start (1 is noise) to data at t = 0. 17.3절
as_metrics
as_metrics(out)A step returns a loss or a dict of metrics; return a dict. 2.4절
assign_anchor_to_bbox
assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5)Assign closest ground-truth bounding boxes to anchor boxes. ?sec-anchor
associative_recall
associative_recall(rng, batch_size, num_pairs, num_keys=512, num_values=4, num_steps=256, num_rebound=0, gap=None)Key-value pairs, filler, then every key again as a query. The first 12.6절
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 and concatenate. 16.5절
batchify
batchify(data)Return a minibatch of examples for skip-gram with negative sampling. ?sec-word2vec-data
bbox_to_rect
bbox_to_rect(bbox, color)Convert bounding box to matplotlib format. ?sec-bbox
beam_search
beam_search(step_fn, prefix, num_tokens, beam_size=4, alpha=0.75, eos_id=None)Length-normalized beam search (score = log P / len^alpha). 8.6.3절
bleu
bleu(pred_seq, label_seq, k)Compute the BLEU. 12.2.2절
box_center_to_corner
box_center_to_corner(boxes)Convert from (center, width, height) to (upper-left, lower-right). ?sec-bbox
box_corner_to_center
box_corner_to_center(boxes)Convert from (upper-left, lower-right) to (center, width, height). ?sec-bbox
box_iou
box_iou(boxes1, boxes2)Compute pairwise IoU across two lists of anchor or bounding boxes. ?sec-anchor
causal_mask
causal_mask(num_queries, num_keys=None)Boolean (queries, keys) mask, True where a query may see a key. 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절
check_shape
check_shape(a, shape)Check the shape of a tensor. 8.4.2절
chrf
chrf(pred, label, n=6, beta=2)chrF (Popovic, 2015): character n-gram F-score. 12.2.2절
chunked_delta_rule
chunked_delta_rule(Q, K, V, beta, log_a, chunk_size)Outputs y_t = S_t q_t of the gated delta rule, computed in chunks. 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절
clip_gradients
clip_gradients(grad_clip_val, grads)Rescale the gradients to global norm at most grad_clip_val. 8.4.2절
clipped_surrogate
clipped_surrogate(rho, adv, epsilon)PPO’s per-sample objective eq_ppo_clip: min(rho A, clip(rho) A). 15.2절
conditional
conditional(net, c)The field (x, t) -> net(x, t, c) with the labels c fixed. 17.4절
copyfile
copyfile(filename, target_dir)Copy a file into a target directory. ?sec-kaggle-cifar10
corr2d
corr2d(X, K)Compute 2D cross-correlation. 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절
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절
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, key=None, t_start=1.0, t_end=0.0)DDIM from x at t_start (1 is noise) to t_end; eta > 0 needs a key. 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절
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절
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절
drop_path
drop_path(key, 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절
embedding_rows
embedding_rows(table, X)The rows X of table. 27.9절
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_loss
evaluate_loss(net, data_iter, loss)Evaluate the loss of a model on the given dataset. 27.9절
extract
extract(filename, folder=None)Extract a zip/tar file into folder. 27.9절
f_valley
f_valley(x1, x2)The ill-conditioned quadratic valley h1/2 x1^2 + h2/2 x2^2, with 9.1절
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, 28, 28, 1) in [-1, 1]. 17.4절
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절
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절
forward_np
forward_np(net, x)net(x) for numpy x, as numpy, through one compiled forward per net 27.9절
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절
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. ?sec-word2vec-data
get_negatives
get_negatives(all_contexts, vocab, counter, K)Return noise words in negative sampling. ?sec-word2vec-data
get_tokens_and_segments
get_tokens_and_segments(tokens_a, tokens_b=None)Get tokens of the BERT input sequence and their segment IDs. ?sec-bert
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_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절
gray_features
gray_features(cnn, x)Features of gray images (n, 28, 28, 1), clipped to [-1, 1]. 17.4절
group_step
group_step(task, theta, K, reward, rng, lr=2.0)verifier_step with the group-normalized weight (GRPO): the rewards 14.8절
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절
init_timescales
init_timescales(layer, dt_min=0.001, dt_max=0.1, rngs)Start a minGRU’s gates at the decays exp(-dt) of S4D. 12.4절
js_mixtures
js_mixtures(mus_q, As_q, mus_p=mu_p, As_p=A_p)JS(p, q) between two known mixtures, p the data by default, by 16.2절
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절
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절
langevin
langevin(score_fn, x, step, num_steps, key)Langevin steps x <- x + step / 2 * score + sqrt(step) * noise. 17.1절
linear_scan
linear_scan(a, b, h0=None)All states of h_t = a_t * h_{t-1} + b_t; time is the second axis. 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절
lm_adamw
lm_adamw(lr=0.0, num_steps=1, warmup=0, weight_decay=0.0, max_norm=1.0)The transformation of LMOptimizer, with its hyperparameters as state. 11.2절
lm_decay_mask
lm_decay_mask(params)Decay the weight matrices; exempt embeddings, gains, and biases. 11.2절
lm_loss_sum
lm_loss_sum(graphdef, state, X, Y)Summed next-token cross-entropy of a batch, and the model’s state. 9.5절
lm_perplexity
lm_perplexity(model, batches)Perplexity of a language model on the minibatches (X, Y) of batches. 9.5절
load_array
load_array(data_arrays, batch_size, is_train=True)Minibatches of JAX arrays, reshuffled each pass if is_train. 27.9절
load_cifar10_arrays
load_cifar10_arrays()CIFAR-10 on the default device, pixel values scaled to [-1, 1]. 27.9절
load_data_bananas
load_data_bananas(batch_size)Load the banana detection dataset. ?sec-object-detection-dataset
load_data_imdb
load_data_imdb(batch_size, num_steps=500)Return data iterators and the vocabulary of the IMDb review dataset. ?sec-sentiment
load_data_ptb
load_data_ptb(batch_size, max_window_size, num_noise_words)Download the PTB dataset and then load it into memory. ?sec-word2vec-data
load_data_snli
load_data_snli(batch_size, num_steps=50)Download the SNLI dataset and return data iterators and vocabulary. ?sec-natural-language-inference-and-dataset
load_data_voc
load_data_voc(batch_size, crop_size)Load the VOC semantic segmentation dataset. ?sec-semantic-segmentation
load_data_wiki
load_data_wiki(batch_size, max_len)Load the WikiText-2 dataset. ?sec-bert-dataset
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_pokemon
load_pokemon(resolution=64)All Pokemon sprites as one (n, h, w, 3) array in [-1, 1]. 16.5절
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_tx, data, lrs, seed, num_steps=2000, evaluate=None, metric='score', every=None, verbose=True)Train make_model(rngs=…) with the optax transformation make_tx(lr) 9.5절
make_critic
make_critic(rngs)Leaky-ReLU MLP; nnx.Linear gives LeCun-normal weights, zero biases. 16.2절
make_mlp
make_mlp(sizes, act, rngs)Linear layers of the given widths with the activation function act 16.1절
make_pred
make_pred(net, path, kind)pred(x, alpha, sigma) -> (x0, eps) from net(x, t) of a kind on path. 17.3절
masked_softmax
masked_softmax(X, mask=None)Softmax over the last axis with zero weight where mask is False. 10.2절
mixture_logpdf
mixture_logpdf(x, mus, As)Log density of the uniform mixture of Gaussians N(mu_k, A_k^T A_k). 16.2절
mixup
mixup(key, X, y, alpha)Mix a minibatch with a shuffled copy; return both label sets. 7.6절
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. ?sec-anchor
multibox_prior
multibox_prior(data, sizes, ratios)Generate anchor boxes with different shapes centered on each pixel. ?sec-anchor
multibox_target
multibox_target(anchors, labels)Label anchor boxes using ground-truth bounding boxes. ?sec-anchor
nms
nms(boxes, scores, iou_threshold)Sort confidence scores of predicted bounding boxes. ?sec-anchor
noise_scale
noise_scale(model, sample, b_small=16, b_big=2048, m=400)Gradient-noise scale from the mean squared gradient norms of m 9.8절
num_correct
num_correct(model, X, y)Number of examples in (X, y) that model classifies correctly. 9.5절
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. ?sec-anchor
offset_inverse
offset_inverse(anchors, offset_preds)Predict bounding boxes based on anchor boxes with predicted offsets. ?sec-anchor
on_grid
on_grid(runs, grid, col, smooth=1)Resample per-episode rows (env step, value, …) onto an env-step 27.9절
padded
padded(*arrays)The arrays zero-padded along axis 0 to a shared bucket length, plus a 27.9절
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절
peak_memory
peak_memory(f, *args)Temporary memory that XLA reserves to run jax.jit(f) on args, in 5.7절
plain_sgd
plain_sgd(net, lr)A plain SGD optimizer over net, one optax.sgd per learning rate. 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절
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절
position_loss_sum
position_loss_sum(model, X, Y)Loss in nats at each position, summed over the batch. 12.1.4절
ppo_epochs
ppo_epochs(ac, obs, act, adv, logp_old, epsilon, num_epochs, entropy_coef=0.01, surrogate=clipped_surrogate)num_epochs passes on the mean surrogate plus an entropy bonus, on one 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. ?sec-sentiment-rnn
predict_snli
predict_snli(net, vocab, premise, hypothesis)Predict the logical relationship between the premise and hypothesis. ?sec-natural-language-inference-attention
print_wrapped
print_wrapped(*args, width=76)Print like print, folding each line to the width of a page. 8.2절
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절
query_accuracy
query_accuracy(model, X, Y)Fraction of queries answered correctly. 12.1.4절
query_step
query_step(model, optimizer, X, Y)One optimizer step on the cross-entropy at the last Y.shape[1] steps. 12.1.4절
r1_r2_penalty
r1_r2_penalty(critic, real, fake)Per-sample squared critic input gradients on real (R1) and fake (R2), 16.4절
r3gan_step
r3gan_step(net_G, net_D, opt_G, opt_D, loss_D, loss_G, gamma, X, z, y, X2, z2, y2)One critic step on X against G(z), one generator step on (X2, z2); 16.5절
read_csv_labels
read_csv_labels(fname)Read fname to return a filename to label dictionary. ?sec-kaggle-cifar10
read_data_bananas
read_data_bananas(is_train=True)Read the banana detection dataset images and labels. ?sec-object-detection-dataset
read_imdb
read_imdb(data_dir, is_train)Read the IMDb review dataset text sequences and labels. ?sec-sentiment
read_ptb
read_ptb()Load the PTB dataset into a list of text lines. ?sec-word2vec-data
read_snli
read_snli(data_dir, is_train)Read the SNLI dataset into premises, hypotheses, and labels. ?sec-natural-language-inference-and-dataset
read_voc_images
read_voc_images(voc_dir, is_train=True)Read all VOC feature and label images. ?sec-semantic-segmentation
regression_loss
regression_loss(path, kind)Squared error of net(x_t, t) against the target of a kind, t ~ U(0, 1). 17.2절
reorg_test
reorg_test(data_dir)Organize the testing set for data loading during prediction. ?sec-kaggle-cifar10
reorg_train_valid
reorg_train_valid(data_dir, labels, valid_ratio)Split the validation set out of the original training set. ?sec-kaggle-cifar10
resnet18
resnet18(num_classes, in_channels=1, rngs)ResNet-18 for small images: a 3x3 stem without max-pooling, He 13.6절
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)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절
run_seeds
run_seeds(train, num_seeds, **kwargs)Run train(seed, **kwargs), a generator of curve points, per seed. 27.9절
sample_mixture
sample_mixture(n, mus, As, rng)n draws from the uniform mixture of Gaussians mu_k + z A_k. 16.2절
sample_real
sample_real(key, images, n, labels=None)Draw a training batch with random horizontal flips; return it with 16.5절
scatter_panels
scatter_panels(samples, titles=None, data=None, lim=4.5, size=3.0)Scatter 2-D point sets side by side on equal, shared axes. 17.1절
set_axes
set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend, legend_loc=None)Set the axes for matplotlib. legend_loc is a matplotlib legend 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절
shift_step
shift_step(critic_loss, gen_loss, gp, one_sided, G, D, opt_G, opt_D, X, Z, U)One critic step per row of U, then one generator step; returns the 16.2절
show_bboxes
show_bboxes(axes, bboxes, labels=None, colors=None)Show bounding boxes. ?sec-anchor
show_gray
show_gray(imgs, num_rows, num_cols, titles=None, scale=1.0)Show images (n, h, w, 1) in [-1, 1], or binary (n, h, w), in gray. 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_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절
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절
subsample
subsample(sentences, vocab)Subsample high-frequency words. ?sec-word2vec-data
synthetic_data
synthetic_data(w, b, noise, n, key)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, rngs)A network with one tanh hidden layer. 14.9절
text_table
text_table(make_model, arms, data, num_runs=2, num_steps=1000)Train num_runs fresh models make_model(*args) for each arm (a name 12.1.4절
tile_images
tile_images(imgs, num_rows)Tile images (n, h, w, 3) in [-1, 1] into one (rows * h, cols * w, 3) 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절
to_bf16
to_bf16(model)Make the linear layers of model compute in bf16; parameters stay 13.4절
tokenize
tokenize(lines, token='word')Split text lines into word or character tokens. 27.9절
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, optimizer, X, y)Train for a minibatch with JAX (defined in Chapter 13). ?sec-image-augmentation
train_ch13
train_ch13(net, train_iter, test_iter, optimizer, num_epochs)Train a model with JAX (defined in Chapter 13). ?sec-image-augmentation
train_delayed_recall
train_delayed_recall(model, num_steps, blank_fillers=False)Train with Adam at rate 0.003 on 1,500 fresh batches of 128 sequences 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_queries
train_queries(model, batch, num_steps, optimizer)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, key, lr=0.001, cosine=False, ema_half_life=1000, chunk=500)Adam on loss_fn(model, batch_fn(k1), k2) -> model, EMA model, losses. 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_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절
train_toy_step
train_toy_step(critic_loss, gen_loss, G, D, opt_G, opt_D, X, z, k)A critic step (unless critic_loss is None), then a generator step. 16.2절
truncate_pad
truncate_pad(line, num_steps, padding_token)Truncate or pad sequences. 27.9절
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절
update_D
update_D(X, Z, net_D, net_G, optimizer_D)Update the critic; return its log loss summed over both batches 16.1절
update_G
update_G(Z, net_D, net_G, optimizer_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절
voc_colormap2label
voc_colormap2label()Build the mapping from RGB to class indices for VOC labels. ?sec-semantic-segmentation
voc_label_indices
voc_label_indices(colormap, colormap2label)Map any RGB values in VOC labels to their class indices. ?sec-semantic-segmentation
voc_rand_crop
voc_rand_crop(feature, label, height, width)Randomly crop both feature and label images. ?sec-semantic-segmentation
windows
windows(corpus, batch_size, num_steps=128, sharding=None)Endless minibatches of windows at random offsets, each position with 13.8절
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절
as_metrics
as_metrics(out)A step returns a loss or a dict of metrics; return a dict. 2.4절
assign_anchor_to_bbox
assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5)Assign closest ground-truth bounding boxes to anchor boxes. ?sec-anchor
batchify
batchify(data)Return a minibatch of examples for skip-gram with negative sampling. ?sec-word2vec-data
bbox_to_rect
bbox_to_rect(bbox, color)Convert bounding box to matplotlib format. ?sec-bbox
beam_search
beam_search(step_fn, prefix, num_tokens, beam_size=4, alpha=0.75, eos_id=None)Length-normalized beam search (score = log P / len^alpha). 8.6.3절
box_center_to_corner
box_center_to_corner(boxes)Convert from (center, width, height) to (upper-left, lower-right). ?sec-bbox
box_corner_to_center
box_corner_to_center(boxes)Convert from (upper-left, lower-right) to (center, width, height). ?sec-bbox
box_iou
box_iou(boxes1, boxes2)Compute pairwise IoU across two lists of anchor or bounding boxes. ?sec-anchor
build_array_nmt
build_array_nmt(lines, vocab, num_steps)Transform text sequences of machine translation into minibatches. 27.9절
check_shape
check_shape(a, shape)Check the shape of a tensor. 8.4.2절
copyfile
copyfile(filename, target_dir)Copy a file into a target directory. ?sec-kaggle-cifar10
corr2d
corr2d(X, K)Compute 2D cross-correlation. 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절
cpu
cpu()Get the CPU device. 5.7절
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절
drop_path
drop_path(Y, p)Zero each example of Y with probability p, rescale the rest. 7.6절
evaluate_accuracy
evaluate_accuracy(net, data_iter)Compute the accuracy for a model on a dataset. 27.9절
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_accuracy_gpus
evaluate_accuracy_gpus(net, data_iter, split_f=d2l.split_batch)Compute the accuracy for a model on a dataset using multiple GPUs. 13.6절
evaluate_loss
evaluate_loss(net, data_iter, loss)Evaluate the loss of a model on the given dataset. 27.9절
extract
extract(filename, folder=None)Extract a zip/tar file into folder. 27.9절
get_centers_and_contexts
get_centers_and_contexts(corpus, max_window_size)Return center words and context words in skip-gram. ?sec-word2vec-data
get_dataloader_workers
get_dataloader_workers()Use 4 processes to read the data except for Windows. 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. ?sec-word2vec-data
get_tokens_and_segments
get_tokens_and_segments(tokens_a, tokens_b=None)Get tokens of the BERT input sequence and their segment IDs. ?sec-bert
gpu
gpu(i=0)Get a GPU device. 5.7절
kneser_ney
kneser_ney(train, tokens, vocab_size, n=3)Interpolated Kneser-Ney log-probabilities (nats) of each of tokens. 8.3절
linreg
linreg(X, w, b)The linear regression model. 27.9절
load_array
load_array(data_arrays, batch_size, is_train=True)Construct a Gluon data iterator. 27.9절
load_checkpoint
load_checkpoint(prefix, model, trainer=None, rng=None)Restore the state written by save_checkpoint; return the metadata. 5.6절
load_data_bananas
load_data_bananas(batch_size)Load the banana detection dataset. ?sec-object-detection-dataset
load_data_fashion_mnist
load_data_fashion_mnist(batch_size, resize=None)Download the Fashion-MNIST dataset and then load it into memory. 27.9절
load_data_imdb
load_data_imdb(batch_size, num_steps=500)Return data iterators and the vocabulary of the IMDb review dataset. ?sec-sentiment
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. ?sec-word2vec-data
load_data_snli
load_data_snli(batch_size, num_steps=50)Download the SNLI dataset and return data iterators and vocabulary. ?sec-natural-language-inference-and-dataset
load_data_voc
load_data_voc(batch_size, crop_size)Load the VOC semantic segmentation dataset. ?sec-semantic-segmentation
load_data_wiki
load_data_wiki(batch_size, max_len)Load the WikiText-2 dataset. ?sec-bert-dataset
mixup
mixup(X, y, alpha)Mix a minibatch with a shuffled copy; return both label sets. 7.6절
multibox_detection
multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5, pos_threshold=0.009999999)Predict bounding boxes using non-maximum suppression. ?sec-anchor
multibox_prior
multibox_prior(data, sizes, ratios)Generate anchor boxes with different shapes centered on each pixel. ?sec-anchor
multibox_target
multibox_target(anchors, labels)Label anchor boxes using ground-truth bounding boxes. ?sec-anchor
nms
nms(boxes, scores, iou_threshold)Sort confidence scores of predicted bounding boxes. ?sec-anchor
num_gpus
num_gpus()Get the number of available GPUs. 5.7절
num_params
num_params(model)The number of trainable parameters. 7.5.1.1절
offset_boxes
offset_boxes(anchors, assigned_bb, eps=1e-06)Transform for anchor box offsets. ?sec-anchor
offset_inverse
offset_inverse(anchors, offset_preds)Predict bounding boxes based on anchor boxes with predicted offsets. ?sec-anchor
plot
plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None, legend_loc=None)Plot data points. 27.9절
predict_sentiment
predict_sentiment(net, vocab, sequence)Predict the sentiment of a text sequence. ?sec-sentiment-rnn
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. ?sec-natural-language-inference-attention
preprocess_nmt
preprocess_nmt(text)Preprocess the English-French dataset. 27.9절
print_wrapped
print_wrapped(*args, width=76)Print like print, folding each line to the width of a page. 8.2절
read_csv_labels
read_csv_labels(fname)Read fname to return a filename to label dictionary. ?sec-kaggle-cifar10
read_data_bananas
read_data_bananas(is_train=True)Read the banana detection dataset images and labels. ?sec-object-detection-dataset
read_data_nmt
read_data_nmt()Load the English-French dataset. 27.9절
read_imdb
read_imdb(data_dir, is_train)Read the IMDb review dataset text sequences and labels. ?sec-sentiment
read_ptb
read_ptb()Load the PTB dataset into a list of text lines. ?sec-word2vec-data
read_snli
read_snli(data_dir, is_train)Read the SNLI dataset into premises, hypotheses, and labels. ?sec-natural-language-inference-and-dataset
read_voc_images
read_voc_images(voc_dir, is_train=True)Read all VOC feature and label images. ?sec-semantic-segmentation
reorg_test
reorg_test(data_dir)Organize the testing set for data loading during prediction. ?sec-kaggle-cifar10
reorg_train_valid
reorg_train_valid(data_dir, labels, valid_ratio)Split the validation set out of the original training set. ?sec-kaggle-cifar10
resnet18
resnet18(num_classes)A slightly modified ResNet-18 model. 13.6절
save_checkpoint
save_checkpoint(prefix, model, trainer, step, cfg=None, rng=None)Replace each component of a resumable MXNet checkpoint. 5.6절
set_axes
set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend, legend_loc=None)Set the axes for matplotlib. legend_loc is a matplotlib legend 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절
show_bboxes
show_bboxes(axes, bboxes, labels=None, colors=None)Show bounding boxes. ?sec-anchor
show_heatmaps
show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5), cmap='Reds', cbar=True, xticklabels=None, yticklabels=None)Show heatmaps of matrices; cbar is True (shared), ‘each’ or False. 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절
split_batch
split_batch(X, y, devices)Split X and y into multiple devices. 13.5절
split_batch_multi_inputs
split_batch_multi_inputs(X, y, devices)Split multi-input X and y into multiple devices. ?sec-natural-language-inference-attention
squared_loss
squared_loss(y_hat, y)Squared loss. 27.9절
subsample
subsample(sentences, vocab)Subsample high-frequency words. ?sec-word2vec-data
synthetic_data
synthetic_data(w, b, noise, n)n examples with standard normal features and labels Xw + b + noise. 2.2절
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절
train_batch_ch13
train_batch_ch13(net, features, labels, loss, trainer, devices, split_f=d2l.split_batch)Train for a minibatch with multiple GPUs (defined in Chapter 13). ?sec-image-augmentation
train_ch13
train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices=d2l.try_all_gpus(), split_f=d2l.split_batch)Train a model with multiple GPUs (defined in Chapter 13). ?sec-image-augmentation
train_ch6
train_ch6(net, train_iter, test_iter, num_epochs, lr, device)Train a model with a GPU (defined in Chapter 6). 27.9절
train_seq2seq
train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device)Train a model for sequence to sequence. 27.9절
truncate_pad
truncate_pad(line, num_steps, padding_token)Truncate or pad sequences. 27.9절
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절
use_svg_display
use_svg_display()Use the svg format to display a plot in Jupyter. 27.9절
voc_colormap2label
voc_colormap2label()Build the mapping from RGB to class indices for VOC labels. ?sec-semantic-segmentation
voc_label_indices
voc_label_indices(colormap, colormap2label)Map any RGB values in VOC labels to their class indices. ?sec-semantic-segmentation
voc_rand_crop
voc_rand_crop(feature, label, height, width)Randomly crop both feature and label images. ?sec-semantic-segmentation