Code
Hub
Workspaces
Following
Trending
Connect
MCP
copy
Create free account
hub
/
github.com/FareedKhan-dev/train-llm-from-scratch
/ functions
Functions
604 in github.com/FareedKhan-dev/train-llm-from-scratch
⨍
Functions
604
◇
Types & classes
40
↓ 22 callers
Method
train
Learn ``vocab_size - 256 - len(special_tokens)`` merges from ``texts``.
src/tokenizer/bpe.py:106
↓ 16 callers
Method
step
(self, closure: Callable[[], float] | None = None)
src/optim/muon.py:96
↓ 14 callers
Function
_model
(cfg: ModernConfig, seed: int = 0)
tests/test_modern_model.py:41
↓ 12 callers
Function
resolve_device
Turn ``"auto"`` or an explicit request into a device string that works on this machine.
src/device.py:33
↓ 11 callers
Function
build_model
Construct a fresh, randomly initialized model described by ``cfg``.
src/models/factory.py:42
↓ 11 callers
Method
encode_ordinary
Encode text with no special-token handling (``<|endoftext|>`` is just characters).
src/tokenizer/bpe.py:194
↓ 11 callers
Method
log
(self, step: int, metrics: dict[str, Any])
src/post_training/logging_utils.py:46
↓ 11 callers
Method
update
Store this step's keys/values for ``layer`` and return everything cached so far.
src/models/modern/kv_cache.py:42
↓ 10 callers
Function
load_model_from_ckpt
Build a model from the settings stored in a checkpoint and load its weights. Works for every checkpoint in the repo: the legacy trainer (set
src/post_training/inference.py:25
↓ 10 callers
Function
masked_mean
Mean of ``values`` over positions where ``mask`` is truthy (safe if mask empty).
src/post_training/utils.py:127
↓ 10 callers
Function
unwrap
Return the plain model behind DDP and torch.compile wrappers (or the model itself).
src/post_training/utils.py:91
↓ 9 callers
Function
amp_autocast
Return a bf16 autocast context on CUDA when requested, else a no-op context. bf16 needs no GradScaler (unlike fp16), which keeps the training loo
src/post_training/utils.py:31
↓ 9 callers
Function
build_model_from_config
Construct a fresh model from a config carrying the standard keys ``n_head, n_embed, context_length, vocab_size, n_blocks`` (plus ``arch`` and
src/post_training/utils.py:60
↓ 9 callers
Function
compute_logprobs
Teacher-forced recomputation of per-token log-probs of ``sequences`` under ``model``. Mirrors the model's training shift: ``logits[:, t]`` p
src/post_training/rollout.py:228
↓ 9 callers
Method
encode
Encode text; special tokens in ``allowed_special`` become their single id.
src/tokenizer/bpe.py:201
↓ 9 callers
Function
generate_with_logprobs
Autoregressively sample a completion for each prompt and record per-token log-probs. ``prompt_ids`` must be (B, P) with a shared length P (l
src/post_training/rollout.py:78
↓ 9 callers
Function
get_batch_iterator
Creates an iterator for generating batches of data from an HDF5 file. The file is cut into windows of ``context_length + 1`` tokens, the win
data_loader/data_loader.py:8
↓ 9 callers
Method
load
(cls, path: str | os.PathLike[str])
src/tokenizer/bpe.py:254
↓ 9 callers
Function
load_config
Resolve ``cfg_cls`` from ``base.json`` + the stage JSON + CLI overrides. Args: cfg_cls: the stage dataclass (e.g. ``SFTConfig``).
config/loader.py:136
↓ 9 callers
Function
save_stage_ckpt
Save a checkpoint in the repo's existing shape (``model_state_dict`` / ``optimizer_state_dict``) plus post-training metadata (``stage``, ``cf
src/post_training/utils.py:159
↓ 8 callers
Method
close
(self)
src/post_training/logging_utils.py:53
↓ 8 callers
Function
filter_logits
Apply temperature, then top-k, top-p and min-p filtering. Returns new logits.
src/inference/sampling.py:25
↓ 8 callers
Method
generate
Generates new tokens given a starting sequence. Args: idx (torch.Tensor): Initial sequence of token indices.
src/models/transformer.py:139
↓ 8 callers
Function
load_backbone_from_ckpt
Build a Transformer from ``cfg`` and load backbone weights from a checkpoint saved by the pretraining script or any post-training stage (``mo
src/post_training/utils.py:75
↓ 8 callers
Function
load_checkpoint
Load a checkpoint dict on any PyTorch version (our files hold metadata, not just tensors).
src/checkpoint.py:67
↓ 8 callers
Function
model_state_from_checkpoint
Return the model weights of a checkpoint with wrapper prefixes removed. Accepts both our checkpoint dicts (weights under ``model_state_dict``) an
src/checkpoint.py:75
↓ 8 callers
Method
save
(self, path: str | os.PathLike[str])
src/tokenizer/bpe.py:248
↓ 8 callers
Function
set_seed
Seed python / numpy / torch (incl. CUDA) for reproducible runs.
src/post_training/utils.py:43
↓ 7 callers
Function
ddp_wrap
Wrap a model in DDP when running multi-GPU; return it unchanged otherwise. Only the *trainable* model should be wrapped. Reference / old-policy /
src/post_training/distributed.py:69
↓ 7 callers
Function
encode_chat
Tokenize a conversation and build an aligned per-token loss mask. The mask is 1 over assistant content (and its terminating EOT) and 0 every
src/post_training/chat_template.py:95
↓ 7 callers
Function
encode_preference_pair
Encode ``prompt + chosen`` and ``prompt + rejected`` into at most ``max_len`` tokens each. The rules, in order: 1. Both sides share the
data_loader/preference_dataset.py:47
↓ 7 callers
Method
forward_hidden
Run the backbone and return the final hidden states AFTER the final layer norm. This is exactly the tensor that ``lm_head`` consumes
src/models/transformer.py:68
↓ 7 callers
Function
grpo_loss
Clipped surrogate + KL penalty, with the variant switches described in the module docstring. Args: new_logp/old_logp/ref_logp: (B, L
src/post_training/grpo.py:111
↓ 7 callers
Function
parse_config_with_json
Like :func:`parse_config`, but resolves the config from a JSON file too. Adds two flags on top of the per-field ``--field`` overrides:
src/post_training/cli.py:64
↓ 7 callers
Function
reduce_scalar
All-reduce a python scalar across ranks (sum or mean). No-op when single-process.
src/post_training/distributed.py:92
↓ 6 callers
Function
_check
(cond: bool, message: str)
config/post_training_config.py:43
↓ 6 callers
Function
_tiny_model
(vocab=64, ctx=32)
tests/test_post_training_smoke.py:25
↓ 6 callers
Function
_weights_equal
(a: nn.Module, b: nn.Module)
tests/test_checkpoint_io.py:32
↓ 6 callers
Function
_windows_file
An h5 whose window i starts with token i, so a batch's first column names its windows.
tests/test_resume_data_order.py:29
↓ 6 callers
Function
apply_rope
Rotate every pair ``(x1, x2)`` of ``x`` by its angle: a 2D rotation per pair.
src/models/modern/rope.py:39
↓ 6 callers
Function
cleanup
(ctx: DDPContext)
src/post_training/distributed.py:108
↓ 6 callers
Function
ddp_setup
Initialize the process group if launched under torchrun; otherwise single-process. ``device`` is ``"auto"`` (CUDA, then Apple MPS, then CPU), or
src/post_training/distributed.py:39
↓ 6 callers
Function
make_frozen_copy
Deep-copy a model, put it in eval mode, and disable all gradients. Used for the DPO/PPO/GRPO reference model and the PPO old-policy snapshot.
src/post_training/utils.py:110
↓ 6 callers
Function
render_stage_page
(stage_key: str)
ui/stage_page.py:17
↓ 6 callers
Function
rope_cache
Precompute ``cos`` and ``sin`` of every angle ``position * theta_i``.
src/models/modern/rope.py:30
↓ 6 callers
Function
score_requests
Score every request, ``batch_size`` at a time, inside a window of ``max_length`` tokens. Each input is the last ``max_length + 1`` tokens of cont
src/benchmarks/scoring.py:67
↓ 6 callers
Function
tokenizer_from_spec
Build a tokenizer from a spec dict (or its JSON string, or a tiktoken name).
src/tokenizer/__init__.py:44
↓ 5 callers
Function
apply_preset
Return a copy of ``config`` with preset ``name`` applied.
config/presets.py:86
↓ 5 callers
Function
check
(name, cond, detail="")
tests/verify_data_and_eval.py:20
↓ 5 callers
Function
configure_optimizer
AdamW with weight decay applied only to >=2D parameters (matrices), not to biases / norms / 1D params. Standard GPT recipe.
src/post_training/optim.py:23
↓ 5 callers
Method
decode
Turn ids back into text. Bytes that are not valid UTF-8 on their own become U+FFFD.
src/tokenizer/bpe.py:214
↓ 5 callers
Function
extract_answer
Extract the model's final numeric answer with graceful fallback: 1) inside an ``<answer>...</answer>`` tag (after its last ``=`` when it hold
src/post_training/rewards/parsing.py:52
↓ 5 callers
Function
group_advantages
Group-relative advantage: ``(r - group_mean) / (group_std + eps)``. ``rewards`` is (num_prompts * group_size,) laid out group-contiguously (
src/post_training/grpo.py:47
↓ 5 callers
Function
gsm8k_gold_answer
Extract the numeric gold answer from a GSM8K ``answer`` field (ends in ``#### N``).
src/post_training/rewards/parsing.py:77
↓ 5 callers
Function
load_model_weights
Copy matching weights from ``state`` into ``model``. Extra keys are ignored (a reward or value head saved next to the backbone, for example)
src/checkpoint.py:99
↓ 5 callers
Function
save
(fig: plt.Figure, name: str)
docs/diagrams/make_plots.py:78
↓ 5 callers
Function
speculative_generate
Generate ``max_new_tokens`` tokens after ``idx`` (batch size 1) with draft-then-verify. ``target_window`` and ``draft_window`` cap how many recen
src/inference/speculative.py:72
↓ 5 callers
Function
tokenizer_spec
The JSON-friendly description of ``tokenizer`` (the inverse of :func:`tokenizer_from_spec`).
src/tokenizer/__init__.py:57
↓ 4 callers
Method
__post_init__
(self)
config/post_training_config.py:144
↓ 4 callers
Function
_alive
(pid: int)
ui/jobs.py:70
↓ 4 callers
Function
_classic
(seed: int, vocab: int = 13)
tests/test_inference.py:18
↓ 4 callers
Function
_json
(tmp_path: Path, data: dict[str, Any])
tests/test_config.py:45
↓ 4 callers
Function
_prompt_len
(mask: list[int])
tests/test_preference_truncation.py:18
↓ 4 callers
Function
apply_lora
Freeze ``model`` and wrap every ``nn.Linear`` whose attribute name is in ``targets`` with a :class:`LoRALinear`. Only the LoRA matrices stay
src/models/lora.py:74
↓ 4 callers
Function
coerce
Convert ``value`` to ``annotation`` (bool/int/float/str/None/Literal/unions) or raise.
config/loader.py:75
↓ 4 callers
Function
compute_gae
Generalized Advantage Estimation over the response. Args (all (B, L) in the action frame; ``resp_mask`` bool): rewards: per-acti
src/post_training/ppo.py:24
↓ 4 callers
Function
cosine_lr
Linear warmup to ``lr`` over ``warmup_steps``, then cosine decay to ``min_lr`` by ``max_steps`` (constant ``min_lr`` afterwards).
src/optim/schedules.py:30
↓ 4 callers
Function
decode
Decode token ids back to text (for eval / verifier parsing / sample dumps). Defensive: drops the EOT terminator and any id >= EOT (50256), s
src/post_training/chat_template.py:145
↓ 4 callers
Function
device_type
``"cuda:1"`` -> ``"cuda"``; used for autocast and for capability checks.
src/device.py:64
↓ 4 callers
Function
encode_prompt
Token ids for the prompt form (ends in the assistant header, ready to generate).
src/post_training/chat_template.py:139
↓ 4 callers
Function
estimate
Parameter counts, FLOPs and memory of the model ``cfg`` describes (no memory used).
scripts/model_report.py:62
↓ 4 callers
Function
field_types
Resolved type of every dataclass field (works with ``from __future__ import annotations``).
config/loader.py:130
↓ 4 callers
Function
get_preference_iterator
Yield collated preference batches (dict of tensors). Rows are sharded across ranks.
data_loader/preference_dataset.py:113
↓ 4 callers
Function
gsm8k_accuracy
Compute greedy GSM8K accuracy over ``(question, answer_field)`` pairs. Returns ``{"accuracy", "n", "correct", "samples"}`` where ``samples``
src/post_training/evaluation.py:77
↓ 4 callers
Function
is_correct
Whether the model's parsed answer matches the gold answer (used for accuracy eval).
src/post_training/rewards/verifiers.py:30
↓ 4 callers
Function
label
Direct label in a text token (never the series color).
docs/diagrams/make_plots.py:85
↓ 4 callers
Function
load_gsm8k_eval
Load ``(question, answer_field)`` pairs from GSM8K for evaluation.
src/post_training/evaluation.py:107
↓ 4 callers
Method
new_cache
An empty KV cache sized for this model (it stores the latent for MLA).
src/models/modern/model.py:118
↓ 4 callers
Method
num_params
Parameter count (tied weights counted once).
src/models/modern/model.py:169
↓ 4 callers
Function
read_registry
(job_id: str)
ui/jobs.py:42
↓ 4 callers
Function
reward_gsm8k
Reward for a GSM8K response: correctness (dominant) + small format bonus, clipped.
src/post_training/rewards/verifiers.py:35
↓ 4 callers
Function
safe_decode
Decode while skipping ids the tokenizer does not know. Models pad their vocabulary (50257 -> 50304 for r50k_base) so the embedding table is a
src/tokenizer/__init__.py:66
↓ 4 callers
Function
set_lr
Set the learning rate of every parameter group (respecting an optional ``lr_scale``).
src/optim/schedules.py:78
↓ 4 callers
Function
sft_loss
Masked next-token cross-entropy. Args: logits: (B, T, V) model logits for ``tokens``. tokens: (B, T) packed token ids.
src/post_training/sft.py:18
↓ 4 callers
Function
smoke
Return an instance of ``cfg_cls`` shrunk to the tiny SMOKE model dims.
config/post_training_config.py:267
↓ 3 callers
Function
_collate
(rows: list[dict], max_len: int, device: str)
data_loader/preference_dataset.py:92
↓ 3 callers
Function
_ids
(it: Any, n: int)
tests/test_resume_data_order.py:38
↓ 3 callers
Function
_kept
(logits: torch.Tensor)
tests/test_sampling.py:13
↓ 3 callers
Function
_logits_from
Get logits whether ``model`` returns ``(logits, loss)`` (Transformer) or ``(logits, values)`` (value-head wrapper) or a bare logits tensor.
src/post_training/rollout.py:65
↓ 3 callers
Function
_merge
Replace every occurrence of ``pair`` in ``ids`` with ``new_id``.
src/tokenizer/bpe.py:47
↓ 3 callers
Function
_model
(n_blocks: int = 3)
tests/test_classic_model.py:10
↓ 3 callers
Method
_pre_attn_pass
Combines token and position embeddings. Args: idx (torch.Tensor): Input token indices. Returns: tor
src/models/transformer.py:53
↓ 3 callers
Function
_warmup
(step: int, warmup_steps: int, lr: float)
src/optim/schedules.py:26
↓ 3 callers
Method
active_params
Parameters used per token: with MoE only ``moe_top_k`` of the routed experts run.
src/models/modern/model.py:174
↓ 3 callers
Function
aggregate_token_loss
Reduce a per-token loss to one number. The choice matters more than it looks: - ``token-mean``: every token in the batch counts the same. Lo
src/post_training/grpo.py:82
↓ 3 callers
Function
attention_mask
Decide how to mask attention. Returns ``(mask, is_causal)`` for SDPA. ``start`` is the position of the first query (the number of cached tok
src/models/modern/attention.py:37
↓ 3 callers
Function
bytes_to_gib
Convert a byte count to gibibytes for human-readable memory reports.
scripts/train_transformer.py:56
↓ 3 callers
Function
checkpoint_path
Build a stable checkpoint path for the last completed training step.
scripts/train_transformer.py:170
↓ 3 callers
Function
configure_cpu_threads
Set how many CPU threads PyTorch uses, and return the number in use. By default PyTorch's own choice is kept (one thread per physical core),
src/device.py:92
↓ 3 callers
Function
encode_pair
Tokenize a (context, continuation) pair the way lm-evaluation-harness does. Trailing whitespace moves from the context to the continuation, and t
src/benchmarks/scoring.py:48
next →
1–100 of 604, ranked by callers