1use std::rc::Rc;
4
5use crate::{DType, Error, Matrix, Result, Runtime, matrix};
6
7use super::super::{Module, ModuleRegistry};
8use super::Linear;
9
10pub struct AdaptiveLogSoftmaxResult {
13 pub output: Matrix,
14 pub loss: Matrix,
15}
16
17pub struct AdaptiveLogSoftmaxWithLoss {
25 in_features: usize,
26 n_classes: usize,
27 cutoffs: Vec<usize>,
28 head: Rc<Linear>,
29 tails: Vec<(Rc<Linear>, Rc<Linear>)>,
30 registry: ModuleRegistry,
31}
32
33impl AdaptiveLogSoftmaxWithLoss {
34 pub fn new(in_features: usize, n_classes: usize, cutoffs: &[usize]) -> Result<Self> {
40 Self::new_with_seed(in_features, n_classes, cutoffs, 0)
41 }
42
43 pub fn new_with_seed(
51 in_features: usize,
52 n_classes: usize,
53 cutoffs: &[usize],
54 seed: u64,
55 ) -> Result<Self> {
56 Self::new_with_seed_on(
57 &Runtime::current()?,
58 in_features,
59 n_classes,
60 cutoffs,
61 4.0,
62 false,
63 true,
64 seed,
65 )
66 }
67
68 #[allow(clippy::too_many_arguments)]
78 pub fn new_with_seed_on(
79 runtime: &Runtime,
80 in_features: usize,
81 n_classes: usize,
82 cutoffs: &[usize],
83 div_value: f64,
84 head_bias: bool,
85 _tail_bias: bool,
86 seed: u64,
87 ) -> Result<Self> {
88 let (head_size, tail_sizes) = validate_adaptive_shape(
89 "AdaptiveLogSoftmaxWithLoss::new_with_seed_on",
90 in_features,
91 n_classes,
92 cutoffs,
93 )?;
94 if div_value <= 0.0 || !div_value.is_finite() {
95 return Err(Error::invalid_argument(format!(
96 "AdaptiveLogSoftmaxWithLoss requires a positive finite div_value; found {div_value}"
97 )));
98 }
99 let head = Rc::new(Linear::new_with_seed_and_bias_on(
100 runtime,
101 in_features,
102 head_size,
103 head_bias,
104 seed,
105 )?);
106 let mut tails = Vec::with_capacity(tail_sizes.len());
107 for (index, size) in tail_sizes.iter().enumerate() {
108 let hidden = (in_features as f64 / div_value.powi(index as i32 + 1))
109 .round()
110 .max(1.0) as usize;
111 let projection = Rc::new(Linear::new_with_seed_and_bias_on(
112 runtime,
113 in_features,
114 hidden,
115 true,
116 seed + 1 + index as u64,
117 )?);
118 let output = Rc::new(Linear::new_with_seed_and_bias_on(
119 runtime,
120 hidden,
121 *size,
122 true,
123 seed + 1 + tail_sizes.len() as u64 + index as u64,
124 )?);
125 tails.push((projection, output));
126 }
127 Self::from_parts(in_features, n_classes, cutoffs, head, tails)
128 }
129
130 pub fn from_parts(
137 in_features: usize,
138 n_classes: usize,
139 cutoffs: &[usize],
140 head: Rc<Linear>,
141 tails: Vec<(Rc<Linear>, Rc<Linear>)>,
142 ) -> Result<Self> {
143 const OPERATION: &str = "AdaptiveLogSoftmaxWithLoss::from_parts";
144 let (head_size, tail_sizes) =
145 validate_adaptive_shape(OPERATION, in_features, n_classes, cutoffs)?;
146 if head.input_features() != in_features || head.output_features() != head_size {
147 return Err(Error::invalid_argument(format!(
148 "{OPERATION} head must map {in_features} inputs to {head_size} outputs"
149 )));
150 }
151 if tails.len() != tail_sizes.len() {
152 return Err(Error::invalid_argument(format!(
153 "{OPERATION} requires {} tail clusters; found {}",
154 tail_sizes.len(),
155 tails.len()
156 )));
157 }
158 for (index, ((projection, output), size)) in tails.iter().zip(&tail_sizes).enumerate() {
159 if projection.input_features() != in_features
160 || output.input_features() != projection.output_features()
161 || output.output_features() != *size
162 {
163 return Err(Error::invalid_argument(format!(
164 "{OPERATION} tail {index} must chain {in_features} -> hidden -> {size}"
165 )));
166 }
167 }
168 let mut registry = ModuleRegistry::new();
169 registry.register_module("head", head.clone())?;
170 for (index, (projection, output)) in tails.iter().enumerate() {
171 registry.register_module(format!("tail_{index}_projection"), projection.clone())?;
172 registry.register_module(format!("tail_{index}_output"), output.clone())?;
173 }
174 Ok(Self {
175 in_features,
176 n_classes,
177 cutoffs: cutoffs.to_vec(),
178 head,
179 tails,
180 registry,
181 })
182 }
183
184 pub fn log_prob(&self, input: &Matrix) -> Result<Matrix> {
191 let (head_log_probs, tail_log_probs, _rows) = self.distributions(input)?;
192 let mut parts = Vec::with_capacity(self.tails.len() + 1);
193 parts.push(matrix::slice(
194 &head_log_probs,
195 1,
196 0,
197 self.cutoffs[0] as i64,
198 )?);
199 for (index, tail_log_probs) in tail_log_probs.iter().enumerate() {
200 let cluster_logit = self.cluster_log_probs(&head_log_probs, index)?;
201 parts.push(matrix::add(tail_log_probs, &cluster_logit)?);
202 }
203 matrix::concat(&parts, 1)
204 }
205
206 pub fn forward(&self, input: &Matrix, target: &Matrix) -> Result<AdaptiveLogSoftmaxResult> {
214 const OPERATION: &str = "AdaptiveLogSoftmaxWithLoss::forward";
215 let (head_log_probs, tail_log_probs, rows) = self.distributions(input)?;
216 if target.shape().len() != 1 || target.shape()[0] != rows {
217 return Err(Error::invalid_argument(format!(
218 "{OPERATION} target must have shape [N] matching the input rows"
219 )));
220 }
221 if !target.runtime().same_as(input.runtime()) {
222 return Err(Error::invalid_argument(format!(
223 "{OPERATION} input and target must belong to the same runtime"
224 )));
225 }
226 let target_f32 = match target.dtype() {
227 DType::F32 => target.clone(),
228 DType::I32 | DType::U32 => matrix::cast_i32_f32(target)?,
229 other => {
230 return Err(Error::invalid_argument(format!(
231 "{OPERATION} requires I32, U32, or F32 targets; found {}",
232 other.token()
233 )));
234 }
235 };
236 let mut previous = matrix::greater_equal(&target_f32, self.cutoffs[0] as f32)?;
239 let mask0 = matrix::add_scalar(&matrix::neg(&previous)?, 1.0)?;
240 let mut masks = Vec::with_capacity(self.tails.len());
241 let boundaries = self
242 .cutoffs
243 .iter()
244 .copied()
245 .skip(1)
246 .chain(std::iter::once(self.n_classes));
247 for upper in boundaries {
248 let next = matrix::greater_equal(&target_f32, upper as f32)?;
249 masks.push(matrix::sub(&previous, &next)?);
250 previous = next;
251 }
252 let mut head_index = matrix::mul(&mask0, &target_f32)?;
255 for (index, mask) in masks.iter().enumerate() {
256 let column_index = (self.cutoffs[0] + index) as f32;
257 let contribution = matrix::div_scalar(mask, 1.0 / column_index)?;
258 head_index = matrix::add(&head_index, &contribution)?;
259 }
260 let head_index = matrix::cast_f32_i32(&head_index)?.reshape([rows, 1])?;
261 let mut nll = matrix::neg(&matrix::gather_last_dim(&head_log_probs, &head_index)?)?;
262 let target_column = target_f32.reshape([rows, 1])?;
263 for (index, tail_log_probs) in tail_log_probs.iter().enumerate() {
264 let local = matrix::sub_scalar(&target_column, self.cutoffs[index] as f32)?;
265 let local = matrix::cast_f32_i32(&local)?;
266 let gathered = matrix::gather_last_dim(tail_log_probs, &local)?;
267 let term = matrix::mul(&gathered, &masks[index].reshape([rows, 1])?)?;
268 nll = matrix::sub(&nll, &term)?;
269 }
270 let loss = matrix::mean(&nll, -1)?.reshape([])?;
271 let mut parts = Vec::with_capacity(self.tails.len() + 1);
272 parts.push(matrix::slice(
273 &head_log_probs,
274 1,
275 0,
276 self.cutoffs[0] as i64,
277 )?);
278 for (index, tail_log_probs) in tail_log_probs.iter().enumerate() {
279 let cluster_logit = self.cluster_log_probs(&head_log_probs, index)?;
280 parts.push(matrix::add(tail_log_probs, &cluster_logit)?);
281 }
282 let output = matrix::concat(&parts, 1)?;
283 Ok(AdaptiveLogSoftmaxResult { output, loss })
284 }
285
286 fn distributions(&self, input: &Matrix) -> Result<(Matrix, Vec<Matrix>, usize)> {
288 const OPERATION: &str = "AdaptiveLogSoftmaxWithLoss";
289 if input.dtype() != DType::F32 || input.shape().len() != 2 {
290 return Err(Error::invalid_argument(format!(
291 "{OPERATION} requires a rank-two FP32 input"
292 )));
293 }
294 if input.shape()[1] != self.in_features {
295 return Err(Error::invalid_argument(format!(
296 "{OPERATION} requires {} input features; found {}",
297 self.in_features,
298 input.shape()[1]
299 )));
300 }
301 let rows = input.shape()[0];
302 let head_log_probs = matrix::log_softmax(&self.head.forward(input)?, -1)?;
303 let mut tail_log_probs = Vec::with_capacity(self.tails.len());
304 for (projection, output) in &self.tails {
305 let logits = output.forward(&projection.forward(input)?)?;
306 tail_log_probs.push(matrix::log_softmax(&logits, -1)?);
307 }
308 Ok((head_log_probs, tail_log_probs, rows))
309 }
310
311 fn cluster_log_probs(&self, head_log_probs: &Matrix, index: usize) -> Result<Matrix> {
314 let rows = head_log_probs.shape()[0];
315 let column = self.cutoffs[0] + index;
316 let index =
317 head_log_probs.new_from_slice_on_same_runtime(vec![rows, 1], &vec![column as i32; rows])?;
318 matrix::gather_last_dim(head_log_probs, &index)
319 }
320
321 pub const fn in_features(&self) -> usize {
323 self.in_features
324 }
325
326 pub const fn n_classes(&self) -> usize {
328 self.n_classes
329 }
330}
331
332impl Module for AdaptiveLogSoftmaxWithLoss {
333 fn forward(&self, input: &Matrix) -> Result<Matrix> {
334 let _ = input;
335 Err(Error::invalid_argument(
336 "AdaptiveLogSoftmaxWithLoss requires a target; call forward(input, target) or log_prob(input)",
337 ))
338 }
339
340 fn registry(&self) -> &ModuleRegistry {
341 &self.registry
342 }
343}
344
345fn validate_adaptive_shape(
347 operation: &'static str,
348 in_features: usize,
349 n_classes: usize,
350 cutoffs: &[usize],
351) -> Result<(usize, Vec<usize>)> {
352 if in_features == 0 || n_classes == 0 || cutoffs.is_empty() {
353 return Err(Error::invalid_argument(format!(
354 "{operation} requires nonzero in_features and n_classes with at least one cutoff"
355 )));
356 }
357 let mut previous = 0usize;
358 for &cutoff in cutoffs {
359 if cutoff <= previous || cutoff >= n_classes {
360 return Err(Error::invalid_argument(format!(
361 "{operation} cutoffs must strictly increase inside 0..{n_classes}"
362 )));
363 }
364 previous = cutoff;
365 }
366 let tail_sizes: Vec<usize> = cutoffs
367 .iter()
368 .copied()
369 .chain(std::iter::once(n_classes))
370 .skip(1)
371 .zip(cutoffs.iter().copied())
372 .map(|(upper, lower)| upper - lower)
373 .collect();
374 Ok((cutoffs[0] + cutoffs.len(), tail_sizes))
375}