Skip to main content

LlamaSampler

Struct LlamaSampler 

Source
pub struct LlamaSampler { /* private fields */ }
Expand description

A sampler: an ordered chain of transform stages ending in a selector, matching llama-cpp-2’s LlamaSampler.

Build single stages with the constructors (greedy, temp, top_k, …) and compose them with chain_simple. During generation, either call sample (which reads logits from the context) or apply on a candidate array you already built, then read LlamaTokenDataArray::selected_token. Call accept with each drawn token so stateful stages (penalties, grammar) stay in sync.

Not Clone (a grammar stage owns a C grammar object freed on drop).

Implementations§

Source§

impl LlamaSampler

Source

pub fn chain_simple(samplers: impl IntoIterator<Item = LlamaSampler>) -> Self

Compose several samplers into one chain, applied left to right.

Source

pub fn greedy() -> Self

Greedy (argmax) selector.

Source

pub fn dist(seed: u32) -> Self

Stochastic distribution selector seeded by seed (softmax + draw).

Source

pub fn temp(t: f32) -> Self

Temperature scaling.

Source

pub fn temp_ext(t: f32, delta: f32, exponent: f32) -> Self

Dynamic-temperature (“entropy”) scaling over [t-delta, t+delta].

Source

pub fn top_k(k: i32) -> Self

Top-k filtering.

Source

pub fn top_p(p: f32, min_keep: usize) -> Self

Top-p (nucleus) filtering.

Source

pub fn min_p(p: f32, min_keep: usize) -> Self

Min-p filtering.

Source

pub fn typical(p: f32, min_keep: usize) -> Self

Locally-typical filtering.

Source

pub fn top_n_sigma(n: f32) -> Self

Top-nσ filtering.

Source

pub fn tail_free(z: f32, min_keep: usize) -> Self

Tail-free filtering.

Source

pub fn grammar( model: &LlamaModel, grammar_str: &str, root: &str, ) -> Result<Self, GrammarInitError>

A GBNF grammar constraint stage.

grammar_str is GBNF source, root the start symbol (usually "root"). The stage masks tokens the grammar cannot currently accept; call accept with each drawn token to advance grammar state.

§Safety contract

The returned sampler stashes a pointer into model’s vocab, so model must outlive this sampler — using it after the model is dropped is undefined behavior. This is not encoded in the type (the sampler stays 'static) so that it drops in for llama-cpp-2, which makes the same choice; keep the model alive at least as long as any sampler built from it (a 'static model trivially satisfies this). Prefer crate::grammar::LlamaGrammar if you want the model lifetime enforced.

§Errors

GrammarInitError::Nul on an interior NUL byte; GrammarInitError::Parse if the GBNF fails to parse.

Source

pub fn grammar_lazy( model: &LlamaModel, grammar_str: &str, root: &str, trigger_words: impl IntoIterator<Item = impl AsRef<[u8]>>, trigger_tokens: &[LlamaToken], ) -> Result<Self, GrammarInitError>

A lazy GBNF grammar constraint: it stays inert until one of trigger_words / trigger_tokens appears, then constrains generation.

§Errors

GrammarInitError::Nul on an interior NUL byte in the grammar, root, or a trigger word; GrammarInitError::Parse if the GBNF fails to parse.

Source

pub fn penalties( penalty_last_n: i32, penalty_repeat: f32, penalty_freq: f32, penalty_present: f32, ) -> Self

Repetition / frequency / presence penalties over the accepted history.

Source

pub fn apply(&mut self, arr: &mut LlamaTokenDataArray)

Run every stage over arr in order (transforms + selector). Read the result with LlamaTokenDataArray::selected_token.

A no-op on an empty candidate array (leaving selected = None): ik’s legacy samplers GGML_ASSERT(size > 0) and would abort the process, so this safe wrapper must not forward an empty set into them.

Source

pub fn accept(&mut self, token: LlamaToken)

Record token: appends to the history (penalties stage) and advances any grammar stage.

If a grammar stage is present, only feed tokens the grammar permits at the current position (i.e. tokens surviving apply). Accepting a grammar-disallowed end-of-generation token aborts the process (ik’s llama_grammar_accept_impl treats it as fatal).

Source

pub fn reset(&mut self)

Clear the accepted-token history.

Source

pub fn sample(&mut self, ctx: &LlamaContext<'_>, idx: i32) -> LlamaToken

Build the candidate array from the context’s logits at batch index idx, run the chain, and return the selected token (argmax fallback if no selector ran).

Trait Implementations§

Source§

impl Debug for LlamaSampler

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more