MCPcopy Create free account

hub / github.com/FareedKhan-dev/train-llm-from-scratch / functions

Functions252 in github.com/FareedKhan-dev/train-llm-from-scratch

↓ 25 callersFunctioncheck
(name, cond, detail="")
tests/verify_data_and_eval.py:20
↓ 19 callersFunctionunwrap
Return the underlying module behind a DDP wrapper (or the model itself).
src/post_training/utils.py:94
↓ 15 callersFunctioncompute_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:233
↓ 14 callersFunctionamp_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:23
↓ 13 callersMethodlog
(self, step: int, metrics: dict[str, Any])
src/post_training/logging_utils.py:46
↓ 12 callersFunctionreduce_scalar
All-reduce a python scalar across ranks (sum or mean). No-op when single-process.
src/post_training/distributed.py:82
↓ 12 callersFunctionsave_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:148
↓ 11 callersFunctionmasked_mean
Mean of ``values`` over positions where ``mask`` is truthy (safe if mask empty).
src/post_training/utils.py:116
↓ 8 callersFunctionreward_gsm8k
Reward for a GSM8K response: correctness (dominant) + small format bonus, clipped.
src/post_training/rewards/verifiers.py:35
↓ 8 callersFunctionset_seed
Seed python / numpy / torch (incl. CUDA) for reproducible runs.
src/post_training/utils.py:35
↓ 7 callersFunction_tiny_model
(vocab=64, ctx=32)
tests/test_post_training_smoke.py:23
↓ 7 callersFunctiongenerate_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:94
↓ 7 callersFunctionmake_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:99
↓ 6 callersFunctioncleanup
(ctx: DDPContext)
src/post_training/distributed.py:98
↓ 6 callersMethodclose
(self)
src/post_training/logging_utils.py:53
↓ 6 callersFunctionconfigure_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:17
↓ 6 callersFunctionddp_setup
Initialize the process group if launched under torchrun; otherwise single-process. Reads ``RANK`` / ``LOCAL_RANK`` / ``WORLD_SIZE`` from the envi
src/post_training/distributed.py:36
↓ 6 callersFunctionddp_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:61
↓ 6 callersFunctiondecode
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
↓ 6 callersFunctionencode_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
↓ 6 callersFunctionextract_answer
Extract the model's final numeric answer with graceful fallback: 1) inside an ``<answer>...</answer>`` tag, else 2) after a GSM8K-style `
src/post_training/rewards/parsing.py:47
↓ 6 callersFunctionparse_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:50
↓ 6 callersFunctionrender_stage_page
(stage_key: str)
ui/stage_page.py:17
↓ 5 callersFunction_cfg_get
Read a field from either a dataclass/object (attr) or a dict.
src/post_training/utils.py:45
↓ 5 callersFunctionbytes_to_gib
Convert a byte count to gibibytes for human-readable memory reports.
scripts/train_transformer.py:27
↓ 5 callersFunctioncompute_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
↓ 5 callersMethodforward_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:63
↓ 5 callersFunctionget_batch_iterator
Creates an iterator for generating batches of data from an HDF5 file. Args: data_path (str): Path to the HDF5 file containing tokeni
data_loader/data_loader.py:6
↓ 5 callersFunctiongsm8k_gold_answer
Extract the numeric gold answer from a GSM8K ``answer`` field (ends in ``#### N``).
src/post_training/rewards/parsing.py:70
↓ 5 callersFunctionload_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:74
↓ 5 callersFunctionparse_number
Parse the first number out of a string, tolerating ``$`` and thousands commas.
src/post_training/rewards/parsing.py:27
↓ 5 callersFunctionsave_training_checkpoint
Save model, optimizer, loss history, and LR schedule metadata. ``step`` is the last completed zero-based training step, so resume starts at
scripts/train_transformer.py:173
↓ 4 callersFunctionbuild_model_from_config
Construct a fresh :class:`Transformer` from a config carrying the standard keys ``n_head, n_embed, context_length, vocab_size, n_blocks``. Wo
src/post_training/utils.py:52
↓ 4 callersFunctioncheckpoint_path
Build a stable checkpoint path for the last completed training step.
scripts/train_transformer.py:113
↓ 4 callersFunctioncosine_lr
Linear warmup to ``lr`` over ``warmup_steps``, then cosine decay to ``min_lr`` by ``max_steps`` (constant ``min_lr`` afterwards).
src/post_training/optim.py:40
↓ 4 callersFunctionencode_prompt
Token ids for the prompt form (ends in the assistant header, ready to generate).
src/post_training/chat_template.py:139
↓ 4 callersFunctionget_preference_iterator
Yield collated preference batches (dict of tensors). Rows are sharded across ranks.
data_loader/preference_dataset.py:55
↓ 4 callersFunctiongroup_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:17
↓ 4 callersFunctiongrpo_loss
Token-level clipped surrogate + KL penalty. Args: new_logp/old_logp/ref_logp: (B, L) per-token log-probs (policy / sampling / ref).
src/post_training/grpo.py:37
↓ 4 callersFunctiongsm8k_accuracy
Compute greedy GSM8K accuracy over ``(question, answer_field)`` pairs. Returns ``{"accuracy", "n", "correct", "samples"}`` where ``samples``
src/post_training/evaluation.py:77
↓ 4 callersFunctionis_correct
Whether the model's parsed answer matches the gold answer (used for accuracy eval).
src/post_training/rewards/verifiers.py:30
↓ 4 callersFunctionload_gsm8k_eval
Load ``(question, answer_field)`` pairs from GSM8K for evaluation.
src/post_training/evaluation.py:107
↓ 4 callersFunctionpad
(seq, fill)
data_loader/preference_dataset.py:39
↓ 4 callersFunctionppo_policy_loss
Clipped surrogate policy loss. Returns (loss, clip_fraction).
src/post_training/ppo.py:68
↓ 4 callersFunctionread_registry
(job_id: str)
ui/jobs.py:42
↓ 3 callersFunction_alive
(pid: int)
ui/jobs.py:53
↓ 3 callersFunction_encode_ordinary
Encode text as ordinary tokens (no special-token handling).
src/post_training/chat_template.py:58
↓ 3 callersFunction_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:52
↓ 3 callersFunction_tiny_model
()
tests/test_checkpoint_resume.py:27
↓ 3 callersFunctionadd
(messages)
scripts/prepare_sft_data.py:66
↓ 3 callersFunctionbatched_generate
Generate a response string for each tokenized prompt, returned in input order. Prompts are grouped by identical length (the model has no pad
src/post_training/evaluation.py:24
↓ 3 callersFunctionget_prompt_iterator
Infinitely yield lists of ``prompts_per_iter`` rows (this rank's shard).
data_loader/prompt_dataset.py:20
↓ 3 callersFunctionget_tokenizer
Return the shared r50k_base encoder (cached so we build it once).
src/post_training/chat_template.py:53
↓ 3 callersFunctionlist_checkpoints
Return periodic checkpoints sorted by training step.
scripts/train_transformer.py:126
↓ 3 callersFunctionload_model_from_ckpt
Build a :class:`Transformer` from a checkpoint's stored cfg and load its backbone weights (tolerates ``module.``/``transformer.`` prefixes and rew
src/post_training/inference.py:19
↓ 3 callersFunctionppo_value_loss
Clipped value-function loss (0.5 * max of clipped/unclipped squared error).
src/post_training/ppo.py:84
↓ 3 callersFunctionwhiten
Normalize advantages to zero mean / unit std over masked (response) positions.
src/post_training/ppo.py:60
↓ 3 callersFunctionwrite_jsonl
(rows, path)
scripts/prepare_rl_prompts.py:24
↓ 2 callersFunction_add_typed
(p: argparse.ArgumentParser, name: str, type_str)
src/post_training/cli.py:16
↓ 2 callersFunction_answers_match
(pred: float | None, gold: float | None)
src/post_training/rewards/verifiers.py:24
↓ 2 callersFunction_coerce_blank
Map an empty text box back to None for optional (``| None``) string fields.
ui/config_forms.py:38
↓ 2 callersFunction_compute_losses
(policy, ref, batch, cfg, ctx)
scripts/train_dpo.py:37
↓ 2 callersFunction_encode_side
(prompt: str, response: str, max_len: int)
data_loader/preference_dataset.py:27
↓ 2 callersFunction_header_for
(role: str)
src/post_training/chat_template.py:63
↓ 2 callersFunction_log
(job_id: str)
ui/jobs.py:33
↓ 2 callersFunction_log1mexp
Numerically stable log(1 - exp(x)) for x < 0.
src/post_training/dpo.py:43
↓ 2 callersFunction_logps
(model, ids, mask, requires_grad)
scripts/train_dpo.py:33
↓ 2 callersFunction_pair_rewards
Forward chosen+rejected in one pass; return (chosen_rewards, rejected_rewards).
scripts/train_reward.py:32
↓ 2 callersMethod_pre_attn_pass
Combines token and position embeddings. Args: idx (torch.Tensor): Input token indices. Returns: tor
src/models/transformer.py:48
↓ 2 callersFunction_reg
(job_id: str)
ui/jobs.py:29
↓ 2 callersFunction_split_hh
Split an HH-RLHF conversation string into (prompt_context, final_response).
scripts/prepare_preference_data.py:25
↓ 2 callersFunction_tiny_config
()
tests/test_checkpoint_resume.py:32
↓ 2 callersFunction_widget
(f, value)
ui/config_forms.py:25
↓ 2 callersFunction_write_json
(path: str, obj: dict)
ui/config_forms.py:45
↓ 2 callersFunction_write_registry
(job_id: str, data: dict)
ui/jobs.py:37
↓ 2 callersFunctionactor_logp_values
One forward through the actor-critic -> (logp, values) in the action frame (B,T-1).
scripts/train_ppo.py:38
↓ 2 callersFunctionas_float
Convert scalar tensors/numbers to plain floats for checkpoint metadata.
scripts/train_transformer.py:288
↓ 2 callersFunctioncollect
(source: str, max_n: int, split: str)
scripts/prepare_preference_data.py:74
↓ 2 callersFunctiondense_reward
Fraction of generated tokens equal to the target token (dense, easy to learn).
tests/verify_rl_optimizes.py:25
↓ 2 callersFunctiondownload_file
Downloads a file from the given URL and saves it with the specified file name. Displays a progress bar using tqdm. Args: url
scripts/data_download.py:12
↓ 2 callersFunctionestimate_loss
Evaluate the model on training and development datasets and calculate average loss. Args: model (Transformer): The model being train
scripts/train_transformer.py:300
↓ 2 callersFunctioneval_accuracy
(rm, cfg, ctx, max_batches: int = 100)
scripts/train_reward.py:43
↓ 2 callersFunctioneval_dev
(model, cfg, ctx, dev_path: str, max_batches: int = 50)
scripts/train_sft.py:34
↓ 2 callersFunctioneval_implicit_acc
(policy, ref, cfg, ctx, max_batches: int = 100)
scripts/train_dpo.py:58
↓ 2 callersFunctionflush
()
scripts/prepare_pretrain_data.py:84
↓ 2 callersFunctiongather_last
Given per-token ``values`` (B, T) and ``seq_lengths`` (B,), return the value at the last real token of each row, i.e. ``values[i, seq_lengths
src/post_training/utils.py:132
↓ 2 callersMethodgenerate
Generates new tokens given a starting sequence. Args: idx (torch.Tensor): Initial sequence of token indices.
src/models/transformer.py:130
↓ 2 callersFunctiongenerate_reply
Generate a response to ``user_text``. - chat mode (default): wraps the prompt in the chat template (optionally with a ``system`` messa
src/post_training/inference.py:37
↓ 2 callersFunctionget_peak_memory_report
Report peak GPU memory (allocated/reserved) since the last reset, or N/A on CPU.
scripts/train_transformer.py:60
↓ 2 callersFunctionget_sft_batch_iterator
Yield ``(tokens, loss_mask, epoch)`` batches from a packed SFT HDF5 file. Rows are sharded across ranks (each rank sees a disjoint stride) s
data_loader/sft_dataset.py:18
↓ 2 callersFunctiongsm8k_prompts
(split: str, limit: int | None)
scripts/prepare_rl_prompts.py:32
↓ 2 callersFunctionhas_well_formed_answer
True iff there is exactly one well-formed ``<answer>...</answer>`` block.
src/post_training/rewards/parsing.py:78
↓ 2 callersFunctionimplicit_accuracy
Fraction of pairs where the implicit (DPO/KTO/ORPO) reward prefers chosen.
src/post_training/dpo.py:93
↓ 2 callersFunctionk3_kl
Per-token unbiased, non-negative KL estimator (Schulman's k3) for KL(policy||ref).
src/post_training/grpo.py:31
↓ 2 callersFunctionload_config
Resolve ``cfg_cls`` from ``base.json`` + the stage JSON + CLI overrides. Args: cfg_cls: the stage dataclass (e.g. ``SFTConfig``).
config/loader.py:48
↓ 2 callersFunctionpreference_accuracy
Fraction of pairs where the model scores the chosen response higher.
src/post_training/reward_train.py:23
↓ 2 callersFunctionprocess_files
Process a specified number of lines from each .jsonl.zst file in the input directory and save encoded tokens to an HDF5 file. Args:
scripts/data_preprocess.py:10
↓ 2 callersFunctionprune_old_checkpoints
Keep only the most recent N periodic checkpoints when requested.
scripts/train_transformer.py:268
↓ 2 callersFunctionreply
(text)
scripts/chat.py:43
↓ 2 callersFunctionresolve_resume_path
Resolve a resume argument. ``--resume`` with no value uses the latest periodic checkpoint in checkpoint_dir. ``--resume path/to/file.pt`
scripts/train_transformer.py:138
next →1–100 of 252, ranked by callers