1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use std::collections::HashSet;

use anyhow::Result;
use candle_core::{Device, Tensor};

use super::{
    generate_parameter::GenerateParameter, model_processor::ModelProcessor, sampler::Sampler,
    FinishReason,
};

pub mod dummy;

pub type TokenProbability = (u32, f32);

#[derive(Debug, PartialEq)]
pub enum TokenGeneratorResult {
    Token(TokenProbability),
    Finish(FinishReason),
}

/// A trait defining the behavior of a token generator.
///
/// This trait is implemented by objects that can generate tokens based on some internal logic.
/// The trait provides methods to initialize the generator and to retrieve the next token in the sequence.
pub trait TokenGeneratorTrait: Send {
    /// Initializes the token generator with a given set of prompt tokens.
    ///
    /// # Arguments
    ///
    /// * `prompt_tokens` - A vector of initial tokens used to start the token generation process.
    ///
    /// # Returns
    ///
    /// A `Result` indicating the success or failure of the initialization.
    fn init(&mut self, prompt_tokens: Vec<u32>) -> Result<()>;

    /// Retrieves the next token from the generator.
    ///
    /// # Returns
    ///
    /// A `Result` containing the `TokenGeneratorResult`, which can be either a token or a signal to finish generation.
    fn next(&mut self) -> Result<TokenGeneratorResult>;
}

/// A token generator that generates tokens based on provided parameters, model processor, and sampler.
///
/// This struct implements the `TokenGeneratorTrait` and provides functionality to generate tokens
/// for text generation tasks.
pub struct TokenGenerator {
    index: usize,
    stop_tokens: HashSet<u32>,
    parameter: GenerateParameter,
    prompt_tokens: Vec<u32>,
    sampler: Box<dyn Sampler>,
    model: Box<dyn ModelProcessor>,
    next_token: Option<u32>,
    all_tokens: Vec<u32>,
}

unsafe impl Send for TokenGenerator {}

impl TokenGenerator {
    /// Creates a new `TokenGenerator` with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `stop_tokens` - A set of token IDs that signal the end of token generation.
    /// * `parameter` - The parameters to use for token generation.
    /// * `model` - A model processor to generate logits.
    /// * `sampler` - A sampler to sample tokens from logits.
    ///
    /// # Returns
    ///
    /// A new instance of `TokenGenerator`.
    pub fn new(
        stop_tokens: HashSet<u32>,
        parameter: GenerateParameter,
        model: Box<dyn ModelProcessor>,
        sampler: Box<dyn Sampler>,
    ) -> Self {
        Self {
            index: 0,
            stop_tokens,
            parameter,
            prompt_tokens: Vec::new(),
            model,
            sampler,
            next_token: None,
            all_tokens: Vec::new(),
        }
    }

    fn next_token(&mut self, input: &[u32]) -> Result<u32> {
        let next_token = {
            let input = Tensor::new(input, &Device::Cpu)?.unsqueeze(0)?;
            let logits = self
                .model
                .forward(&input, self.prompt_tokens.len() + self.index)?;
            let logits = logits.squeeze(0)?;

            let adjusted_logits = if self.parameter.repeat_penalty != 1.0 {
                self.apply_repeat_penalty(&logits)?
            } else {
                logits
            };
            self.sampler.sample(&adjusted_logits)?
        };
        Ok(next_token)
    }

    fn apply_repeat_penalty(&self, logits: &Tensor) -> Result<Tensor> {
        let start_at = self
            .all_tokens
            .len()
            .saturating_sub(self.parameter.repeat_last_n);
        let logits = candle_transformers::utils::apply_repeat_penalty(
            logits,
            self.parameter.repeat_penalty,
            &self.all_tokens[start_at..],
        )?;
        Ok(logits.clone())
    }
}

impl TokenGeneratorTrait for TokenGenerator {
    fn init(&mut self, prompt_tokens: Vec<u32>) -> Result<()> {
        self.prompt_tokens = prompt_tokens.clone();
        self.all_tokens = prompt_tokens.clone();

        self.next_token = Some(
            self.next_token(prompt_tokens.as_slice())
                .unwrap_or_default(),
        );
        Ok(())
    }

    fn next(&mut self) -> Result<TokenGeneratorResult> {
        if self.index >= self.parameter.max_new_tokens {
            return Ok(TokenGeneratorResult::Finish(FinishReason::Length));
        }

        let next_token = self.next_token(&[self.next_token.unwrap_or_default()])?;

        if self.stop_tokens.contains(&next_token) {
            return Ok(TokenGeneratorResult::Finish(FinishReason::EosToken));
        }
        self.next_token = Some(next_token);
        self.all_tokens.push(next_token);
        self.index += 1;
        Ok(TokenGeneratorResult::Token((next_token, 1.0)))
    }
}

#[cfg(test)]
mod tests {
    use crate::llm::{model_processor::DummyModelProcessor, sampler::DummySampler};

    use super::*;

    #[test]
    fn test_token_generator_finish() {
        let mut token_generator = TokenGenerator::new(
            HashSet::new(),
            GenerateParameter {
                max_new_tokens: 10,
                repeat_penalty: 1.0,
                ..Default::default()
            },
            Box::new(DummyModelProcessor::new()),
            Box::new(DummySampler::new()),
        );
        token_generator.init(vec![0, 1, 2]).unwrap();
        // starting at 1 because model processor and sampler run already in the new function.
        for index in 1..11 {
            assert_eq!(
                token_generator.next().unwrap(),
                TokenGeneratorResult::Token((index, 1.0))
            );
        }
        assert_eq!(
            token_generator.next().unwrap(),
            TokenGeneratorResult::Finish(FinishReason::Length)
        );
    }

    #[test]
    fn test_token_generator_eos_token() {
        let stop_token = 3;
        let mut token_generator = TokenGenerator::new(
            vec![stop_token].into_iter().collect(),
            GenerateParameter {
                max_new_tokens: 10,
                repeat_penalty: 1.0,
                ..Default::default()
            },
            Box::new(DummyModelProcessor::new()),
            Box::new(DummySampler::new()),
        );
        token_generator.init(vec![0, 1, 2]).unwrap();
        for index in 1..3 {
            assert_eq!(
                token_generator.next().unwrap(),
                TokenGeneratorResult::Token((index, 1.0))
            );
        }
        assert_eq!(
            token_generator.next().unwrap(),
            TokenGeneratorResult::Finish(FinishReason::EosToken)
        );
    }
}