LLM Developer DocsLLM Docs

Loading the search index ...

↑ ↓ move, Enter open, Esc close

GitHub

generate.py

Sampling and the generation loop

Where it fits

2 of 2 functions, classes and methods here are reachable from train.main, and 2 from talk.main.

Pipeline stageStepExplained on
GenerationGenerationautoregressive generation

Imports and used by

Imports from this repository
ops.py, transformer.py
Other imports
numpy
Imported by
talk.py, tests/test_generate.py, train.py
Used by, in the pipeline
talk.py, train.py
Used by, in tests
tests/test_generate.py

Mathematics used

ConceptWhat this file doesLinesStatus
Greedy guardComputes it8, 9Implemented
SoftmaxCalls it11Implemented
TemperatureComputes it11Implemented
Top-kComputes it13, 14, 15, 16Derived from implementation
Top-pComputes it18, 19, 20, 21, 23, 24Derived from implementation
Random choiceComputes it26Implemented
Autoregressive loopComputes it31, 32, 33Implemented

Functions and constants

Source

generate.py35 linesGitHub: generate.py
# the probabilities are transformed into wordsfrom ops import softmax_forwardfrom transformer import ModelConfig, forwardimport numpy as npdef sample_next(logits, temperature, top_k, top_p, rng):    if temperature < 1e-6:        return int(np.argmax(logits))    p = softmax_forward(logits / temperature)    if 0 < top_k < len(p):        cutoff = np.sort(p)[-top_k] # # k-th largest probabilit        p = np.where(p >= cutoff, p, 0.0) # zero everything below it        p = p / p.sum() # renormalise so it sums to 1 again    if top_p < 1.0:        order = np.argsort(-p)        cum = np.cumsum(p[order])        keep = order[: np.searchsorted(cum, top_p) + 1]        q = np.zeros_like(p)        q[keep] = p[keep]        p = q / q.sum()    return int(rng.choice(len(p), p=p))def generate(params, cfg: ModelConfig, seed_ids, max_new_tokens, window, temperature, top_k, top_p, rng):    ids = list(seed_ids)    for _ in range(max_new_tokens):        logits, _ = forward(params, np.array(ids[-window:]), cfg)        ids.append(sample_next(logits[-1], temperature, top_k, top_p, rng)) # logits[-1] is used because the last position is the only one that has seen the whole context    return ids