1use std::{cell::Cell, rc::Rc};
6
7use crate::{DType, Error, Matrix, Result, Runtime, matrix};
8
9use super::super::{Module, ModuleRegistry, Parameter, autograd};
10
11use super::{AttentionMode, LayerNorm, Linear, TransformerBlock};
12
13pub struct FlowTimeEmbedding {
17 embedding_dim: usize,
18 max_period: f32,
19 time_scale: f32,
20 frequencies: Matrix,
21 registry: ModuleRegistry,
22}
23
24impl FlowTimeEmbedding {
25 pub fn new(embedding_dim: usize, max_period: f32, time_scale: f32) -> Result<Self> {
26 Self::new_on(&Runtime::current()?, embedding_dim, max_period, time_scale)
27 }
28
29 pub fn new_on(
37 runtime: &Runtime,
38 embedding_dim: usize,
39 max_period: f32,
40 time_scale: f32,
41 ) -> Result<Self> {
42 if embedding_dim == 0
43 || !embedding_dim.is_multiple_of(2)
44 || !max_period.is_finite()
45 || max_period <= 1.0
46 || !time_scale.is_finite()
47 || time_scale <= 0.0
48 {
49 return Err(Error::invalid_argument(
50 "FlowTimeEmbedding requires a positive even dimension, finite max period greater than one, and finite positive scale",
51 ));
52 }
53 let half = embedding_dim / 2;
54 let log_period = max_period.ln();
55 let frequencies = (0..half)
56 .map(|index| time_scale * (-log_period * index as f32 / half as f32).exp())
57 .collect::<Vec<_>>();
58 let frequencies = Matrix::new_from_f32_on(runtime, [1, half], &frequencies)?;
59 let mut registry = ModuleRegistry::new();
60 registry.register_buffer("frequencies", frequencies.clone(), false)?;
61 Ok(Self {
62 embedding_dim,
63 max_period,
64 time_scale,
65 frequencies,
66 registry,
67 })
68 }
69
70 pub fn forward(&self, time: &Matrix) -> Result<Matrix> {
77 let batch = match time.shape() {
78 [batch] => *batch,
79 [batch, 1] => *batch,
80 _ => {
81 return Err(Error::invalid_argument(
82 "FlowTimeEmbedding expects F32 [B] or [B, 1]",
83 ));
84 }
85 };
86 if time.dtype() != DType::F32 || !time.runtime().same_as(self.frequencies.runtime()) {
87 return Err(Error::invalid_argument(
88 "FlowTimeEmbedding expects same-runtime F32 [B] or [B, 1]",
89 ));
90 }
91 let time = matrix::reshape(time, [batch, 1])?;
92 let phase = matrix::mul(&time, &self.frequencies)?;
93 matrix::concat(&[matrix::sin(&phase)?, matrix::cos(&phase)?], 1)
94 }
95
96 pub const fn embedding_dim(&self) -> usize {
98 self.embedding_dim
99 }
100
101 pub const fn max_period(&self) -> f32 {
103 self.max_period
104 }
105
106 pub const fn time_scale(&self) -> f32 {
108 self.time_scale
109 }
110}
111
112impl Module for FlowTimeEmbedding {
113 fn forward(&self, input: &Matrix) -> Result<Matrix> {
114 FlowTimeEmbedding::forward(self, input)
115 }
116
117 fn registry(&self) -> &ModuleRegistry {
118 &self.registry
119 }
120}
121
122#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct FlowTransformerConfig {
125 pub model_width: usize,
126 pub hidden_width: usize,
127 pub sequence_length: usize,
128 pub num_layers: usize,
129 pub num_heads: usize,
130 pub num_experts: usize,
131 pub experts_per_token: usize,
132 pub epsilon: f32,
133 pub adaptive_conditioning: bool,
134}
135
136impl Default for FlowTransformerConfig {
137 fn default() -> Self {
138 Self {
139 model_width: 0,
140 hidden_width: 0,
141 sequence_length: 0,
142 num_layers: 1,
143 num_heads: 1,
144 num_experts: 0,
145 experts_per_token: 0,
146 epsilon: 1.0e-5,
147 adaptive_conditioning: true,
148 }
149 }
150}
151
152pub struct FlowTransformer {
154 config: Cell<FlowTransformerConfig>,
155 blocks: Vec<Rc<TransformerBlock>>,
156 output_norm: Rc<LayerNorm>,
157 registry: ModuleRegistry,
158}
159
160impl FlowTransformer {
161 #[allow(clippy::too_many_arguments)]
162 pub fn new_with_seed(config: FlowTransformerConfig, seed: u64) -> Result<Self> {
163 Self::new_with_seed_on(&Runtime::current()?, config, seed)
164 }
165
166 pub fn new_with_seed_on(
173 runtime: &Runtime,
174 config: FlowTransformerConfig,
175 seed: u64,
176 ) -> Result<Self> {
177 validate_config(config)?;
178 let mut registry = ModuleRegistry::new();
179 let mut blocks = Vec::with_capacity(config.num_layers);
180 for index in 0..config.num_layers {
181 let block_seed = seed.wrapping_add((index as u64).wrapping_mul(16));
182 let block = if config.num_experts == 0 {
183 if config.adaptive_conditioning {
184 TransformerBlock::new_with_seed_conditioned_on(
185 runtime,
186 config.model_width,
187 config.hidden_width,
188 config.sequence_length,
189 config.num_heads,
190 config.model_width,
191 config.epsilon,
192 block_seed,
193 )?
194 } else {
195 TransformerBlock::new_with_seed_on(
196 runtime,
197 config.model_width,
198 config.hidden_width,
199 config.sequence_length,
200 config.num_heads,
201 config.epsilon,
202 block_seed,
203 )?
204 }
205 } else if config.adaptive_conditioning {
206 TransformerBlock::new_with_seed_moe_conditioned_on(
207 runtime,
208 config.model_width,
209 config.hidden_width,
210 config.sequence_length,
211 config.num_heads,
212 config.num_experts,
213 config.experts_per_token,
214 config.model_width,
215 config.epsilon,
216 block_seed,
217 )?
218 } else {
219 TransformerBlock::new_with_seed_moe_on(
220 runtime,
221 config.model_width,
222 config.hidden_width,
223 config.sequence_length,
224 config.num_heads,
225 config.num_experts,
226 config.experts_per_token,
227 config.epsilon,
228 block_seed,
229 )?
230 };
231 block.set_attention_mode(AttentionMode::Bidirectional);
232 let block = Rc::new(block);
233 registry.register_module(format!("block_{index}"), block.clone())?;
234 blocks.push(block);
235 }
236 let output_norm = Rc::new(LayerNorm::new_on(
237 runtime,
238 config.model_width,
239 config.epsilon,
240 )?);
241 registry.register_module("output_norm", output_norm.clone())?;
242 Ok(Self {
243 config: Cell::new(config),
244 blocks,
245 output_norm,
246 registry,
247 })
248 }
249
250 pub fn forward(&self, tokens: &Matrix) -> Result<Matrix> {
252 self.forward_impl(tokens, None, None)
253 }
254
255 pub fn forward_masked(&self, tokens: &Matrix, token_mask: &Matrix) -> Result<Matrix> {
257 self.forward_impl(tokens, Some(token_mask), None)
258 }
259
260 pub fn forward_conditioned(
262 &self,
263 tokens: &Matrix,
264 condition: &Matrix,
265 token_mask: Option<&Matrix>,
266 ) -> Result<Matrix> {
267 self.forward_impl(tokens, token_mask, Some(condition))
268 }
269
270 fn forward_impl(
271 &self,
272 tokens: &Matrix,
273 token_mask: Option<&Matrix>,
274 condition: Option<&Matrix>,
275 ) -> Result<Matrix> {
276 let config = self.config.get();
277 let (batch, rows, batched) = match tokens.shape() {
278 [rows, features]
279 if *features == config.model_width
280 && *rows != 0
281 && rows.is_multiple_of(config.sequence_length) =>
282 {
283 (rows / config.sequence_length, *rows, false)
284 }
285 [batch, sequence, features]
286 if *features == config.model_width
287 && *sequence == config.sequence_length
288 && *batch != 0 =>
289 {
290 (
291 *batch,
292 batch.checked_mul(*sequence).ok_or_else(|| {
293 Error::invalid_argument("FlowTransformer token row count overflows usize")
294 })?,
295 true,
296 )
297 }
298 _ => {
299 return Err(Error::invalid_argument(
300 "FlowTransformer expects F32 [B*S,D] or [B,S,D] matching its configured geometry",
301 ));
302 }
303 };
304 if tokens.dtype() != DType::F32 {
305 return Err(Error::invalid_argument(
306 "FlowTransformer tokens must be F32",
307 ));
308 }
309 if let Some(condition) = condition
310 && (!config.adaptive_conditioning
311 || condition.shape() != [batch, config.model_width]
312 || condition.dtype() != DType::F32
313 || !tokens.runtime().same_as(condition.runtime()))
314 {
315 return Err(Error::invalid_argument(
316 "FlowTransformer condition requires enabled same-runtime F32 [B,D] adaptive conditioning",
317 ));
318 }
319
320 let additive_mask = token_mask
321 .map(|mask| self.additive_mask(tokens, mask, batch, config))
322 .transpose()?;
323 let mut output = if batched {
324 matrix::reshape(tokens, [rows, config.model_width])?
325 } else {
326 tokens.clone()
327 };
328 for block in &self.blocks {
329 output = match (condition, additive_mask.as_ref()) {
330 (Some(condition), Some(mask)) => {
331 block.forward_conditioned_masked(&output, condition, mask)?
332 }
333 (Some(condition), None) => block.forward_conditioned(&output, condition)?,
334 (None, Some(mask)) => block.forward_masked(&output, mask)?,
335 (None, None) => block.forward(&output)?,
336 };
337 }
338 let output = self.output_norm.forward(&output)?;
339 if batched {
340 matrix::reshape(&output, tokens.shape().to_vec())
341 } else {
342 Ok(output)
343 }
344 }
345
346 fn additive_mask(
347 &self,
348 tokens: &Matrix,
349 mask: &Matrix,
350 batch: usize,
351 config: FlowTransformerConfig,
352 ) -> Result<Matrix> {
353 let valid_shape = mask.shape() == [batch, config.sequence_length]
354 || mask.shape() == [batch, config.sequence_length, 1];
355 if !valid_shape || mask.dtype() != DType::F32 || !tokens.runtime().same_as(mask.runtime()) {
356 return Err(Error::invalid_argument(
357 "FlowTransformer token mask must be same-runtime F32 [B,S] or [B,S,1]",
358 ));
359 }
360 let key_mask = matrix::reshape(mask, [batch, 1, config.sequence_length])?;
361 let key_mask = matrix::scale(&matrix::sub_scalar(&key_mask, 1.0)?, 1.0e4)?;
362 let repeats = config
363 .num_heads
364 .checked_mul(config.sequence_length)
365 .ok_or_else(|| Error::invalid_argument("FlowTransformer mask repeat count overflows"))?;
366 let additive = matrix::repeat_interleave(&key_mask, repeats, 1)?;
367 let mask_rows = batch
368 .checked_mul(repeats)
369 .ok_or_else(|| Error::invalid_argument("FlowTransformer mask row count overflows"))?;
370 matrix::reshape(&additive, [mask_rows, config.sequence_length])
371 }
372
373 pub fn set_sequence_length(&self, sequence_length: usize) -> Result<()> {
375 if sequence_length == 0 {
376 return Err(Error::invalid_argument(
377 "FlowTransformer sequence length must be positive",
378 ));
379 }
380 for block in &self.blocks {
381 block.set_sequence_length(sequence_length)?;
382 }
383 let mut config = self.config.get();
384 config.sequence_length = sequence_length;
385 self.config.set(config);
386 Ok(())
387 }
388
389 pub fn config(&self) -> FlowTransformerConfig {
390 self.config.get()
391 }
392
393 pub fn is_moe(&self) -> bool {
394 self.config.get().num_experts > 0
395 }
396
397 pub fn num_layers(&self) -> usize {
398 self.blocks.len()
399 }
400
401 pub fn block(&self, index: usize) -> Option<&TransformerBlock> {
402 self.blocks.get(index).map(Rc::as_ref)
403 }
404}
405
406impl Module for FlowTransformer {
407 fn forward(&self, input: &Matrix) -> Result<Matrix> {
408 FlowTransformer::forward(self, input)
409 }
410
411 fn registry(&self) -> &ModuleRegistry {
412 &self.registry
413 }
414}
415
416fn validate_config(config: FlowTransformerConfig) -> Result<()> {
417 let dense = config.num_experts == 0 && config.experts_per_token == 0;
418 let moe = config.num_experts > 0
419 && config.experts_per_token > 0
420 && config.experts_per_token <= config.num_experts;
421 if config.model_width == 0
422 || config.hidden_width == 0
423 || config.sequence_length == 0
424 || config.num_layers == 0
425 || config.num_heads == 0
426 || !config.model_width.is_multiple_of(config.num_heads)
427 || !config.epsilon.is_finite()
428 || config.epsilon <= 0.0
429 || !(dense || moe)
430 {
431 return Err(Error::invalid_argument(
432 "FlowTransformer requires positive geometry, D divisible by H, finite positive epsilon, and either 0/0 dense experts or 0 < K <= E",
433 ));
434 }
435 Ok(())
436}
437
438#[derive(Clone, Copy, Debug, PartialEq)]
440pub struct FlowDenoiserConfig {
441 pub input_dim: usize,
442 pub condition_dim: usize,
443 pub backbone: FlowTransformerConfig,
444 pub time_max_period: f32,
445 pub time_scale: f32,
446 pub condition_dropout_probability: f32,
448}
449
450impl Default for FlowDenoiserConfig {
451 fn default() -> Self {
452 Self {
453 input_dim: 0,
454 condition_dim: 0,
455 backbone: FlowTransformerConfig::default(),
456 time_max_period: 10_000.0,
457 time_scale: 1_000.0,
458 condition_dropout_probability: 0.0,
459 }
460 }
461}
462
463pub struct FlowDenoiser {
465 config: FlowDenoiserConfig,
466 input_projection: Rc<Linear>,
467 time_embedding: Rc<FlowTimeEmbedding>,
468 condition_projection: Option<Rc<Linear>>,
469 backbone: Rc<FlowTransformer>,
470 output_projection: Rc<Linear>,
471 position: Parameter,
472 registry: ModuleRegistry,
473}
474
475impl FlowDenoiser {
476 #[allow(clippy::too_many_arguments)]
477 pub fn new_with_seed(config: FlowDenoiserConfig, seed: u64) -> Result<Self> {
478 Self::new_with_seed_on(&Runtime::current()?, config, seed)
479 }
480
481 pub fn new_with_seed_on(
488 runtime: &Runtime,
489 config: FlowDenoiserConfig,
490 seed: u64,
491 ) -> Result<Self> {
492 if config.input_dim == 0
493 || config.backbone.model_width == 0
494 || config.backbone.sequence_length == 0
495 || !config.time_max_period.is_finite()
496 || config.time_max_period <= 1.0
497 || !config.time_scale.is_finite()
498 || config.time_scale <= 0.0
499 || !config.condition_dropout_probability.is_finite()
500 || !(0.0..1.0).contains(&config.condition_dropout_probability)
501 {
502 return Err(Error::invalid_argument(
503 "FlowDenoiser requires positive input/model/sequence/time geometry and finite condition dropout in [0, 1)",
504 ));
505 }
506 if !config.backbone.adaptive_conditioning {
507 return Err(Error::invalid_argument(
508 "FlowDenoiser requires adaptive conditioning in its backbone",
509 ));
510 }
511
512 let input_projection = Rc::new(Linear::new_with_seed_on(
513 runtime,
514 config.input_dim,
515 config.backbone.model_width,
516 seed,
517 )?);
518 let time_embedding = Rc::new(FlowTimeEmbedding::new_on(
519 runtime,
520 config.backbone.model_width,
521 config.time_max_period,
522 config.time_scale,
523 )?);
524 let condition_projection = if config.condition_dim == 0 {
525 None
526 } else {
527 Some(Rc::new(Linear::new_with_seed_on(
528 runtime,
529 config.condition_dim,
530 config.backbone.model_width,
531 seed.wrapping_add(1),
532 )?))
533 };
534 let backbone = Rc::new(FlowTransformer::new_with_seed_on(
535 runtime,
536 config.backbone,
537 seed.wrapping_add(2),
538 )?);
539 let output_projection = Rc::new(Linear::new_with_seed_on(
540 runtime,
541 config.backbone.model_width,
542 config.input_dim,
543 seed.wrapping_add(3),
544 )?);
545 let position_count = config
546 .backbone
547 .sequence_length
548 .checked_mul(config.backbone.model_width)
549 .ok_or_else(|| Error::invalid_argument("FlowDenoiser position size overflows usize"))?;
550 let position_template = Matrix::allocate(
551 &runtime.handle(),
552 vec![config.backbone.sequence_length, config.backbone.model_width],
553 position_count,
554 DType::F32,
555 )?;
556 let position = matrix::philox_normal(&position_template, 0.0, 0.02, seed.wrapping_add(4))?;
557 let position = Parameter::new("position", position)?;
558
559 let mut registry = ModuleRegistry::new();
560 registry.register_parameter("position", position.clone())?;
561 registry.register_module("input_projection", input_projection.clone())?;
562 registry.register_module("time_embedding", time_embedding.clone())?;
563 if let Some(condition_projection) = &condition_projection {
564 registry.register_module("condition_projection", condition_projection.clone())?;
565 }
566 registry.register_module("backbone", backbone.clone())?;
567 registry.register_module("output_projection", output_projection.clone())?;
568 Ok(Self {
569 config,
570 input_projection,
571 time_embedding,
572 condition_projection,
573 backbone,
574 output_projection,
575 position,
576 registry,
577 })
578 }
579
580 pub fn forward(&self, sample: &Matrix) -> Result<Matrix> {
582 let batch = self.validate_sample(sample)?;
583 let time = zero_matrix(sample, vec![batch, 1])?;
584 let condition = if self.config.condition_dim == 0 {
585 None
586 } else {
587 Some(zero_matrix(sample, vec![batch, self.config.condition_dim])?)
588 };
589 self.forward_conditioned(sample, &time, condition.as_ref(), None)
590 }
591
592 pub fn forward_conditioned(
599 &self,
600 sample: &Matrix,
601 time: &Matrix,
602 condition: Option<&Matrix>,
603 token_mask: Option<&Matrix>,
604 ) -> Result<Matrix> {
605 let batch = self.validate_sample(sample)?;
606 let time_valid =
607 matches!(time.shape(), [value] if *value == batch) || time.shape() == [batch, 1];
608 if !time_valid || time.dtype() != DType::F32 || !sample.runtime().same_as(time.runtime()) {
609 return Err(Error::invalid_argument(
610 "FlowDenoiser time must be same-runtime F32 [B] or [B,1]",
611 ));
612 }
613 match (self.config.condition_dim, condition) {
614 (0, None) => {}
615 (0, Some(_)) => {
616 return Err(Error::invalid_argument(
617 "FlowDenoiser was configured without condition features",
618 ));
619 }
620 (width, Some(value))
621 if value.shape() == [batch, width]
622 && value.dtype() == DType::F32
623 && sample.runtime().same_as(value.runtime()) => {}
624 _ => {
625 return Err(Error::invalid_argument(
626 "FlowDenoiser condition must be same-runtime F32 [B,condition_dim]",
627 ));
628 }
629 }
630
631 let rows = batch
632 .checked_mul(self.config.backbone.sequence_length)
633 .ok_or_else(|| Error::invalid_argument("FlowDenoiser row count overflows usize"))?;
634 let sample_rows = matrix::reshape(sample, [rows, self.config.input_dim])?;
635 let tokens = self.input_projection.forward(&sample_rows)?;
636 let tokens = matrix::reshape(
637 &tokens,
638 [
639 batch,
640 self.config.backbone.sequence_length,
641 self.config.backbone.model_width,
642 ],
643 )?;
644 autograd::record_parameter_leaf(&self.position)?;
645 let position = matrix::reshape(
646 &self.position.data(),
647 [
648 1,
649 self.config.backbone.sequence_length,
650 self.config.backbone.model_width,
651 ],
652 )?;
653 let tokens = matrix::add(&tokens, &position)?;
654 let mut context = self.time_embedding.forward(time)?;
655 if let (Some(projection), Some(condition)) = (&self.condition_projection, condition) {
656 let condition = if self.is_training() && self.config.condition_dropout_probability > 0.0 {
657 let seed_column = matrix::slice(condition, 1, 0, 1)?;
658 let ones = matrix::add_scalar(&matrix::scale(&seed_column, 0.0)?, 1.0)?;
659 let keep = matrix::scale(
660 &matrix::dropout(&ones, self.config.condition_dropout_probability, 0)?,
661 1.0 - self.config.condition_dropout_probability,
662 )?;
663 matrix::mul(condition, &keep)?
664 } else {
665 condition.clone()
666 };
667 context = matrix::add(&context, &projection.forward(&condition)?)?;
668 }
669 let hidden = self
670 .backbone
671 .forward_conditioned(&tokens, &context, token_mask)?;
672 let hidden = matrix::reshape(&hidden, [rows, self.config.backbone.model_width])?;
673 let output = self.output_projection.forward(&hidden)?;
674 matrix::reshape(&output, sample.shape().to_vec())
675 }
676
677 pub fn forward_guided(
679 &self,
680 sample: &Matrix,
681 time: &Matrix,
682 condition: &Matrix,
683 guidance_scale: f32,
684 token_mask: Option<&Matrix>,
685 ) -> Result<Matrix> {
686 if self.condition_projection.is_none() || !guidance_scale.is_finite() || guidance_scale < 0.0 {
687 return Err(Error::invalid_argument(
688 "FlowDenoiser guidance requires configured conditions and a finite nonnegative scale",
689 ));
690 }
691 let _eval = self.scoped_eval();
692 let unconditional_condition = zero_matrix(condition, condition.shape().to_vec())?;
693 let unconditional =
694 self.forward_conditioned(sample, time, Some(&unconditional_condition), token_mask)?;
695 let conditional = self.forward_conditioned(sample, time, Some(condition), token_mask)?;
696 matrix::add(
697 &unconditional,
698 &matrix::scale(&matrix::sub(&conditional, &unconditional)?, guidance_scale)?,
699 )
700 }
701
702 fn validate_sample(&self, sample: &Matrix) -> Result<usize> {
703 let [batch, sequence, features] = sample.shape() else {
704 return Err(Error::invalid_argument(
705 "FlowDenoiser sample must be F32 [B,S,input_dim]",
706 ));
707 };
708 if *batch == 0
709 || *sequence != self.config.backbone.sequence_length
710 || *features != self.config.input_dim
711 || sample.dtype() != DType::F32
712 {
713 return Err(Error::invalid_argument(
714 "FlowDenoiser sample must be nonempty F32 [B,S,input_dim] matching its configuration",
715 ));
716 }
717 Ok(*batch)
718 }
719
720 pub const fn config(&self) -> FlowDenoiserConfig {
721 self.config
722 }
723
724 pub fn is_moe(&self) -> bool {
725 self.backbone.is_moe()
726 }
727
728 pub fn backbone(&self) -> &FlowTransformer {
729 &self.backbone
730 }
731
732 pub fn position(&self) -> Parameter {
733 self.position.clone()
734 }
735}
736
737impl Module for FlowDenoiser {
738 fn forward(&self, input: &Matrix) -> Result<Matrix> {
739 FlowDenoiser::forward(self, input)
740 }
741
742 fn registry(&self) -> &ModuleRegistry {
743 &self.registry
744 }
745}
746
747fn zero_matrix(reference: &Matrix, shape: Vec<usize>) -> Result<Matrix> {
748 let count = shape.iter().try_fold(1_usize, |count, extent| {
749 count
750 .checked_mul(*extent)
751 .ok_or_else(|| Error::invalid_argument("zero Matrix shape overflows usize"))
752 })?;
753 Matrix::allocate(reference.runtime(), shape, count, DType::F32)
754}