Skip to main content

SamplingConfig

Struct SamplingConfig 

Source
pub struct SamplingConfig {
    pub max_new_tokens: usize,
    pub temperature: f32,
    pub top_p: f32,
    pub top_k: usize,
    pub cfg_scale: f32,
    pub seed: u64,
}
Expand description

Sampling knobs for AceStepLm::generate_codes.

Fields§

§max_new_tokens: usize§temperature: f32§top_p: f32

Nucleus sampling threshold (0.9 officially; 1.0 disables).

§top_k: usize

Top-k limit; 0 disables (official default).

§cfg_scale: f32

Classifier-free guidance scale for code generation (2.0 officially; 1.0 disables the unconditional branch).

§seed: u64

Implementations§

Source§

impl SamplingConfig

Source

pub fn new(max_new_tokens: usize, seed: u64) -> Self

Official ACE-Step 1.5 phase-2 defaults: temperature 0.85, top-p 0.9, top-k disabled, CFG 2.0.

Examples found in repository?
examples/lm_forward_probe.rs (line 69)
13fn main() -> anyhow::Result<()> {
14    let model_dir = std::env::args()
15        .nth(1)
16        .unwrap_or_else(|| "/home/meka/repos/ace".to_string());
17    let model_dir = Path::new(&model_dir);
18    let device = Default::default();
19
20    let config = Qwen3Config::load(&model_dir.join("lm_config.json"))?;
21    let lm = AceStepLm::<B>::from_burnpack(&config, &model_dir.join("acestep-lm.bpk"), &device)?;
22    let vocab = AudioCodeVocab::from_tokenizer_json(&model_dir.join("lm_tokenizer.json"))?;
23
24    let cot = lm::build_cot_block(
25        "Metal guitar with a lot of distortion",
26        Some(120.0),
27        Some("A minor"),
28        Some("4/4"),
29        4,
30    );
31    let prompt = lm::build_codes_prompt("Metal guitar with a lot of distortion", &cot);
32    let ids = lm::tokenize_prompt(&model_dir.join("lm_tokenizer.json"), &prompt)?;
33    println!("prompt: {} tokens", ids.len());
34
35    // One full forward; inspect logits at the last position.
36    let model: &Qwen3Model<B> = &lm.model;
37    let ids_i64: Vec<i64> = ids.iter().map(|&id| i64::from(id)).collect();
38    let len = ids_i64.len();
39    let input = Tensor::<B, 2, Int>::from_data(TensorData::new(ids_i64, [1, len]), &device);
40    let hidden = model.forward(input, true);
41    let [_, _, hidden_dim] = hidden.dims();
42    let last = hidden.narrow(1, len - 1, 1).reshape([1, hidden_dim]);
43    let weight = model.embedding_weight();
44    let logits = last
45        .matmul(weight.clone().transpose())
46        .reshape([config.vocab_size as usize]);
47    let values: Vec<f32> = logits
48        .into_data()
49        .convert::<f32>()
50        .to_vec()
51        .map_err(|e| anyhow::anyhow!("{e}"))?;
52    let mut order: Vec<usize> = (0..values.len()).collect();
53    order.sort_by(|&a, &b| values[b].total_cmp(&values[a]));
54    println!("\ntop-10 next-token predictions:");
55    for &idx in order.iter().take(10) {
56        let id = idx as u32;
57        let label = vocab
58            .token_id_to_code(id)
59            .map(|c| format!("audio_code_{c}"))
60            .unwrap_or_else(|| format!("token {id}"));
61        println!("  id {id:>7} logit {:>8.3}  {label}", values[idx]);
62    }
63
64    // Greedy generation (temperature ~0) vs sampled (official defaults).
65    let greedy = SamplingConfig {
66        temperature: 1e-5,
67        top_k: 1,
68        cfg_scale: 1.0,
69        ..SamplingConfig::new(28, 0)
70    };
71    for (name, sampling) in [
72        ("greedy", greedy),
73        ("sampled official", SamplingConfig::new(28, 0)),
74    ] {
75        let codes = lm.generate_codes(&ids, None, &vocab, &sampling, None);
76        println!("\n{name}: {} codes: {codes:?}", codes.len());
77    }
78
79    // Greedy generation via FULL forward each step (no KV cache) to isolate
80    // the incremental path.
81    let mut full_ids = ids.clone();
82    let mut full_codes = Vec::new();
83    for _ in 0..20 {
84        let ids_i64: Vec<i64> = full_ids.iter().map(|&id| i64::from(id)).collect();
85        let len = ids_i64.len();
86        let input = Tensor::<B, 2, Int>::from_data(TensorData::new(ids_i64, [1, len]), &device);
87        let hidden = model.forward(input, true);
88        let last = hidden.narrow(1, len - 1, 1).reshape([1, hidden_dim]);
89        let logits = last
90            .matmul(weight.clone().transpose())
91            .reshape([config.vocab_size as usize]);
92        let values: Vec<f32> = logits
93            .into_data()
94            .convert::<f32>()
95            .to_vec()
96            .map_err(|e| anyhow::anyhow!("{e}"))?;
97        let next = values
98            .iter()
99            .enumerate()
100            .max_by(|(_, a), (_, b)| a.total_cmp(b))
101            .map(|(i, _)| i as u32)
102            .unwrap();
103        if next == AudioCodeVocab::IM_END_ID {
104            break;
105        }
106        if let Some(code) = vocab.token_id_to_code(next) {
107            full_codes.push(code);
108        }
109        full_ids.push(next);
110    }
111    println!(
112        "\nfull-forward greedy: {} codes: {full_codes:?}",
113        full_codes.len()
114    );
115    Ok(())
116}

Trait Implementations§

Source§

impl Clone for SamplingConfig

Source§

fn clone(&self) -> SamplingConfig

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for SamplingConfig

Source§

impl Debug for SamplingConfig

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<C> CloneExpand for C
where C: Clone,

Source§

fn __expand_clone_method(&self, _scope: &mut Scope) -> C

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> IntoComptime for T

Source§

fn comptime(self) -> Self

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeSendSync for T

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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> TuneInputs for T
where T: Clone + Send + Sync + 'static,

Source§

type At<'a> = T

The concrete input type at lifetime 'a.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,