davanstrien/gists / sys1-unpadded-flash /unpadded-flash.diff
davanstrien's picture
download
raw
13.5 kB
diff --git a/src/models/laya.rs b/src/models/laya.rs
index 48fe721..297ff17 100644
--- a/src/models/laya.rs
+++ b/src/models/laya.rs
@@ -1,7 +1,8 @@
use super::AttentionImplementation;
use super::DecisionModel;
use super::modernbert::{
- AttentionOptions, Config as ModernBertConfig, Encoder as ModernBertEncoder,
+ AttentionOptions, Config as ModernBertConfig, Encoder as ModernBertEncoder, Packed,
+ packed_attention,
};
use crate::{
device,
@@ -161,6 +162,35 @@ impl HeadLayer {
}
}
+impl HeadLayer {
+ fn forward_packed(&self, xs: &Tensor, packed: &Packed<'_>) -> candle_core::Result<Tensor> {
+ let (tokens, hidden) = xs.dims2()?;
+ let size = hidden / self.heads;
+ let qkv = xs
+ .apply(&self.norm1)?
+ .to_dtype(self.compute_dtype)?
+ .apply(&self.qkv)?
+ .reshape((tokens, 3, self.heads, size))?;
+ let q = qkv.narrow(1, 0, 1)?.squeeze(1)?;
+ let k = qkv.narrow(1, 1, 1)?.squeeze(1)?;
+ let v = qkv.narrow(1, 2, 1)?.squeeze(1)?;
+ let scale = (size as f64).powf(-0.5);
+ let attention = packed_attention(&q, &k, &v, packed, scale, None, self.attention)?
+ .reshape((tokens, hidden))?
+ .apply(&self.projection)?
+ .to_dtype(xs.dtype())?;
+ let xs = (xs + attention)?;
+ let feed_forward = xs
+ .apply(&self.norm2)?
+ .to_dtype(self.compute_dtype)?
+ .apply(&self.linear1)?
+ .relu()?
+ .apply(&self.linear2)?
+ .to_dtype(xs.dtype())?;
+ xs + feed_forward
+ }
+}
+
pub struct Laya {
tokenizer: tokenizer::Tokenizer,
encoder: ModernBertEncoder,
@@ -177,6 +207,8 @@ pub struct Laya {
cls_id: u32,
sep_id: u32,
mask_id: u32,
+ /// Run padded batches without padding (packed tokens) instead of padding to the longest row.
+ packed: bool,
}
impl Laya {
@@ -269,6 +301,12 @@ impl Laya {
cls_id,
sep_id,
mask_id,
+ // Prototype switch: SYS1_PACKED=0/1 overrides the default (on with Flash Attention).
+ packed: match std::env::var("SYS1_PACKED").as_deref() {
+ Ok("0") => false,
+ Ok("1") => true,
+ _ => attention != AttentionImplementation::Eager,
+ },
})
}
@@ -388,6 +426,13 @@ impl Laya {
let (unique, indices) = deduplicate(&items);
let batch = unique.len();
let length = unique.iter().map(|item| item.ids.len()).max().unwrap_or(0);
+ if self.packed && unique.iter().any(|item| item.ids.len() != length) {
+ let output = self.forward_packed(&unique, length)?;
+ return Ok(indices
+ .into_iter()
+ .map(|index| output[index].clone())
+ .collect());
+ }
let mut ids = vec![self.pad_id; batch * length];
let mut mask = vec![0f32; batch * length];
let mut kinds = Vec::with_capacity(batch);
@@ -436,6 +481,63 @@ impl Laya {
.collect())
}
+ /// Mixed-length batch without padding: concatenate every sequence and keep the offsets.
+ fn forward_packed(&self, items: &[&Item], max_length: usize) -> anyhow::Result<Vec<Vec<f32>>> {
+ let lengths: Vec<_> = items.iter().map(|item| item.ids.len()).collect();
+ let tokens = lengths.iter().sum();
+ let mut ids = Vec::with_capacity(tokens);
+ let mut positions = Vec::with_capacity(tokens);
+ let mut kinds = Vec::with_capacity(tokens);
+ let mut cumulative = Vec::with_capacity(items.len() + 1);
+ let mut markers = Vec::new();
+ let mut counts = Vec::with_capacity(items.len());
+ cumulative.push(0u32);
+ for item in items {
+ let offset = ids.len();
+ ids.extend_from_slice(&item.ids);
+ positions.extend(0..item.ids.len() as u32);
+ kinds.extend(std::iter::repeat_n(
+ item.question.kind as u32,
+ item.ids.len(),
+ ));
+ cumulative.push(ids.len() as u32);
+ markers.extend(item.markers.iter().map(|marker| (offset + marker) as u32));
+ counts.push(item.markers.len());
+ }
+ let marker_count = markers.len();
+ let ids = Tensor::from_vec(ids, tokens, &self.device)?;
+ let positions = Tensor::from_vec(positions, tokens, &self.device)?;
+ let kinds = Tensor::from_vec(kinds, tokens, &self.device)?;
+ let cumulative = Tensor::from_vec(cumulative, items.len() + 1, &self.device)?;
+ let markers = Tensor::from_vec(markers, marker_count, &self.device)?;
+ let packed = Packed {
+ positions: &positions,
+ cumulative: &cumulative,
+ lengths: &lengths,
+ max_length,
+ };
+ let mut hidden = self
+ .encoder
+ .forward_packed(&ids, &packed)
+ .context("encoder forward (packed)")?;
+ hidden = (hidden + kinds.apply(&self.type_embedding)?)?;
+ for (index, layer) in self.head.iter().enumerate() {
+ hidden = layer
+ .forward_packed(&hidden, &packed)
+ .with_context(|| format!("decision head layer {index} (packed)"))?;
+ }
+ let logits = self.score(&hidden.index_select(&markers, 0)?)?;
+ let mut offset = 0;
+ Ok(counts
+ .into_iter()
+ .map(|count| {
+ let values = logits[offset..offset + count].to_vec();
+ offset += count;
+ values
+ })
+ .collect())
+ }
+
fn score_rows(&self, hidden: &Tensor, items: &[&Item]) -> anyhow::Result<Vec<Vec<f32>>> {
let mut output = Vec::with_capacity(items.len());
for (row, item) in items.iter().enumerate() {
@@ -698,7 +800,7 @@ impl DecisionModel for Laya {
let outputs = match self.forward(&prepared) {
Ok(outputs) => outputs,
Err(error) => {
- let message = error.to_string();
+ let message = format!("{error:#}");
return slots
.into_iter()
.map(|slot| slot.and_then(|_| Err(ApiError::new(message.clone()))))
diff --git a/src/models/modernbert.rs b/src/models/modernbert.rs
index 27ab0cf..7617ba0 100644
--- a/src/models/modernbert.rs
+++ b/src/models/modernbert.rs
@@ -97,6 +97,38 @@ impl RotaryEmbedding {
}
}
+/// Token layout of a padding-free batch: every sequence concatenated along one axis.
+pub(super) struct Packed<'a> {
+ /// Position of each token inside its own sequence, shape `[tokens]`.
+ pub positions: &'a Tensor,
+ /// Cumulative sequence lengths, shape `[batch + 1]`.
+ pub cumulative: &'a Tensor,
+ pub lengths: &'a [usize],
+ pub max_length: usize,
+}
+
+impl RotaryEmbedding {
+ /// Rotary embeddings for packed `[tokens, heads, head_size]` queries and keys.
+ fn apply_packed(&self, q: &Tensor, k: &Tensor, positions: &Tensor) -> Result<(Tensor, Tensor)> {
+ let dtype = q.dtype();
+ let rotary_dtype = self.cos.dtype();
+ let cos = self.cos.index_select(positions, 0)?.contiguous()?;
+ let sin = self.sin.index_select(positions, 0)?.contiguous()?;
+ let rotate = |xs: &Tensor| -> Result<Tensor> {
+ let xs = xs
+ .to_dtype(rotary_dtype)?
+ .transpose(0, 1)?
+ .unsqueeze(0)?
+ .contiguous()?;
+ candle_nn::rotary_emb::rope(&xs, &cos, &sin)?
+ .squeeze(0)?
+ .transpose(0, 1)?
+ .to_dtype(dtype)
+ };
+ Ok((rotate(q)?, rotate(k)?))
+ }
+}
+
struct Attention {
qkv: Linear,
projection: Linear,
@@ -196,6 +228,121 @@ impl Attention {
}
}
+impl Attention {
+ fn forward_packed(
+ &self,
+ xs: &Tensor,
+ packed: &Packed<'_>,
+ window: Option<usize>,
+ ) -> Result<Tensor> {
+ let (tokens, hidden) = xs.dims2()?;
+ let qkv = xs
+ .to_dtype(self.compute_dtype)?
+ .apply(&self.qkv)?
+ .reshape((tokens, 3, self.heads, self.head_size))?;
+ let q = qkv.narrow(1, 0, 1)?.squeeze(1)?;
+ let k = qkv.narrow(1, 1, 1)?.squeeze(1)?;
+ let v = qkv.narrow(1, 2, 1)?.squeeze(1)?;
+ let (q, k) = self.rotary.apply_packed(&q, &k, packed.positions)?;
+ let scale = (self.head_size as f64).powf(-0.5);
+ packed_attention(&q, &k, &v, packed, scale, window, self.implementation)?
+ .reshape((tokens, hidden))?
+ .apply(&self.projection)
+ }
+}
+
+/// Attention over packed `[tokens, heads, head_size]` tensors, one sequence at a time.
+pub(super) fn packed_attention(
+ q: &Tensor,
+ k: &Tensor,
+ v: &Tensor,
+ packed: &Packed<'_>,
+ scale: f64,
+ window: Option<usize>,
+ implementation: AttentionImplementation,
+) -> Result<Tensor> {
+ if implementation != AttentionImplementation::Eager {
+ return flash_attention_packed(q, k, v, packed, scale as f32, window, implementation);
+ }
+ // Reference path for backends without Flash Attention: one eager call per sequence.
+ let mut output = Vec::with_capacity(packed.lengths.len());
+ let mut offset = 0;
+ for &length in packed.lengths {
+ let slice = |tensor: &Tensor| -> Result<Tensor> {
+ tensor
+ .narrow(0, offset, length)?
+ .transpose(0, 1)?
+ .unsqueeze(0)?
+ .contiguous()
+ };
+ let mask = window
+ .map(|window| local_attention_mask(length, window, q.dtype(), q.device()))
+ .transpose()?;
+ let attention = eager_attention(&slice(q)?, &slice(k)?, &slice(v)?, scale, mask.as_ref())?;
+ output.push(attention.squeeze(0)?.transpose(0, 1)?.contiguous()?);
+ offset += length;
+ }
+ Tensor::cat(&output, 0)
+}
+
+#[cfg(any(feature = "flash-attn-2", feature = "flash-attn-3"))]
+fn flash_attention_packed(
+ q: &Tensor,
+ k: &Tensor,
+ v: &Tensor,
+ packed: &Packed<'_>,
+ scale: f32,
+ window: Option<usize>,
+ implementation: AttentionImplementation,
+) -> Result<Tensor> {
+ let (q, k, v) = (q.contiguous()?, k.contiguous()?, v.contiguous()?);
+ match implementation {
+ #[cfg(feature = "flash-attn-2")]
+ AttentionImplementation::FlashAttention2 => candle_flash_attn::flash_attn_varlen_windowed(
+ &q,
+ &k,
+ &v,
+ packed.cumulative,
+ packed.cumulative,
+ packed.max_length,
+ packed.max_length,
+ scale,
+ window,
+ window,
+ ),
+ #[cfg(feature = "flash-attn-3")]
+ AttentionImplementation::FlashAttention3 => {
+ candle_flash_attn_v3::flash_attn_varlen_windowed(
+ &q,
+ &k,
+ &v,
+ packed.cumulative,
+ packed.cumulative,
+ packed.max_length,
+ packed.max_length,
+ scale,
+ window,
+ window,
+ false,
+ )
+ }
+ _ => candle_core::bail!("{} support is not compiled in", implementation.cli_name()),
+ }
+}
+
+#[cfg(not(any(feature = "flash-attn-2", feature = "flash-attn-3")))]
+fn flash_attention_packed(
+ _q: &Tensor,
+ _k: &Tensor,
+ _v: &Tensor,
+ _packed: &Packed<'_>,
+ _scale: f32,
+ _window: Option<usize>,
+ implementation: AttentionImplementation,
+) -> Result<Tensor> {
+ candle_core::bail!("{} support is not compiled in", implementation.cli_name())
+}
+
pub(super) struct AttentionOptions<'a> {
pub mask: Option<&'a Tensor>,
pub implementation: AttentionImplementation,
@@ -514,6 +661,32 @@ impl Layer {
}
}
+impl Layer {
+ fn forward_packed(
+ &self,
+ xs: &Tensor,
+ packed: &Packed<'_>,
+ local_window: usize,
+ ) -> Result<Tensor> {
+ let normalized = match &self.attention_norm {
+ Some(norm) => xs.apply(norm)?,
+ None => xs.clone(),
+ };
+ let attention = self
+ .attention
+ .forward_packed(
+ &normalized,
+ packed,
+ self.uses_local_attention.then_some(local_window),
+ )?
+ .to_dtype(xs.dtype())?;
+ let xs = (attention + xs)?;
+ let mlp = xs.apply(&self.mlp_norm)?.apply(&self.mlp)?;
+ let dtype = xs.dtype();
+ xs + mlp.to_dtype(dtype)?
+ }
+}
+
pub struct Encoder {
embeddings: Embedding,
norm: LayerNorm,
@@ -608,6 +781,16 @@ impl Encoder {
xs.apply(&self.final_norm)
}
+ /// Forward over packed token ids of shape `[tokens]`; no padding is ever computed.
+ pub(super) fn forward_packed(&self, ids: &Tensor, packed: &Packed<'_>) -> Result<Tensor> {
+ let local_window = self.local_attention_size / 2;
+ let mut xs = ids.apply(&self.embeddings)?.apply(&self.norm)?;
+ for layer in &self.layers {
+ xs = layer.forward_packed(&xs, packed, local_window)?;
+ }
+ xs.apply(&self.final_norm)
+ }
+
fn local_mask(&self, length: usize, device: &Device) -> Result<Tensor> {
let mut masks = self
.local_masks

Xet Storage Details

Size:
13.5 kB
·
Xet hash:
604a2a26b93e064a646852f687215458f4a8e91f74bdb8b3738f4dd2f4684e63

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.