//! CUDA-capable Candle tensor implementation of Falcon-H1 inference. //! All projection, convolution, attention, and Mamba recurrence tensors remain //! on the selected device. Only input token IDs and final logits cross to CPU. //! The Mamba scan is a reference *sequential* scan (not fused SSD CUDA kernel). //! This backend is for INFERENCE; distillation/training is not implemented here. use std::collections::HashMap; use candle_core::{DType, Device, Result, Tensor as CTensor}; use candle_nn::ops; use crate::{validate_weights, Config, Weights}; pub struct CandleModel { pub config: Config, pub device: Device, weights: HashMap, group_index: CTensor, mup: CTensor, } impl CandleModel { pub fn new(config: Config, weights: Weights, device: Device) -> std::result::Result { validate_weights(&config, &weights)?; let mut mapped = HashMap::with_capacity(weights.len()); for (name, w) in weights { let is_linear = w.shape.len()==2 && name.ends_with(".weight") && name!="model.embed_tokens.weight"; let t = if is_linear { let (rows,cols)=(w.shape[0],w.shape[1]); let mut transposed=vec![0f32;rows*cols]; for row in 0..rows {for col in 0..cols { transposed[col*rows+row]=w.data[row*cols+col]; }} CTensor::from_vec(transposed,(cols,rows),&device) } else { CTensor::from_vec(w.data,w.shape,&device) }.map_err(|e|format!("{name}: {e}"))?; mapped.insert(name, t); } let p = config.mamba_dim * 2 + 2 * config.groups * config.state + config.mamba_heads; let parts = [config.mamba_dim, config.mamba_dim, config.groups*config.state, config.groups*config.state, config.mamba_heads]; let mut scale = Vec::with_capacity(p); for (len, factor) in parts.into_iter().zip(config.ssm_multipliers) { scale.extend(std::iter::repeat(config.ssm_in_multiplier * factor).take(len)); } let mup = CTensor::from_vec(scale, (1, p), &device).map_err(|e|e.to_string())?; let ids = (0..config.mamba_heads) .map(|h| (h/(config.mamba_heads/config.groups)) as u32).collect::>(); let group_index= CTensor::from_vec(ids, config.mamba_heads, &device).map_err(|e|e.to_string())?; Ok(Self { config, device, weights:mapped, group_index, mup }) } pub fn device_name(&self) -> &'static str { match self.device { Device::Cuda(_) => "cuda", Device::Cpu => "cpu-candle", Device::Metal(_) => "metal" } } fn w(&self, name: &str) -> &CTensor { &self.weights[name] } fn linear(&self, x: &CTensor, name: &str) -> Result { x.matmul(self.w(name)) } fn norm(&self, x: &CTensor, name: &str) -> Result { let denom = x.sqr()?.mean_keepdim(1)?.affine(1., self.config.eps as f64)?.sqrt()?; x.broadcast_div(&denom)?.broadcast_mul(self.w(name)) } fn rope(&self, input: &CTensor, n:usize, heads:usize, cos:&CTensor, sin:&CTensor)->Result { let hd=self.config.head_dim; let x=input.reshape((n,heads,hd))?; let a=x.narrow(2,0,hd/2)?; let b=x.narrow(2,hd/2,hd/2)?; let real=a.broadcast_mul(cos)?.broadcast_sub(&b.broadcast_mul(sin)?)?; let imag=b.broadcast_mul(cos)?.broadcast_add(&a.broadcast_mul(sin)?)?; CTensor::cat(&[real,imag],2) } fn rope_tables(&self,n:usize)->Result<(CTensor,CTensor)>{ let hd=self.config.head_dim; let mut cs=Vec::with_capacity(n*hd/2); let mut sn=Vec::with_capacity(n*hd/2); for t in 0..n { for j in 0..hd/2 { let a=(t as f32)/self.config.rope_theta.powf((2*j) as f32/hd as f32); let (s,c)=a.sin_cos();cs.push(c);sn.push(s); }} Ok((CTensor::from_vec(cs,(n,1,hd/2),&self.device)?, CTensor::from_vec(sn,(n,1,hd/2),&self.device)?)) } fn attention(&self, x:&CTensor, prefix:&str, n:usize, cos:&CTensor, sin:&CTensor, mask:&CTensor)->Result{ let c=&self.config; let a=x.affine(c.attention_in_multiplier as f64,0.)?; let q=self.linear(&a,&format!("{prefix}self_attn.q_proj.weight"))?; let k=self.linear(&a,&format!("{prefix}self_attn.k_proj.weight"))? .affine(c.key_multiplier as f64,0.)?; let v=self.linear(&a,&format!("{prefix}self_attn.v_proj.weight"))?; let q=self.rope(&q,n,c.heads,cos,sin)?; let k=self.rope(&k,n,c.kv_heads,cos,sin)?; let v=v.reshape((n,c.kv_heads,c.head_dim))?; let mut heads=Vec::with_capacity(c.heads); for h in 0..c.heads { let kv=h/(c.heads/c.kv_heads); let qi=q.narrow(1,h,1)?.squeeze(1)?.contiguous()?; let ki=k.narrow(1,kv,1)?.squeeze(1)?.contiguous()?; let vi=v.narrow(1,kv,1)?.squeeze(1)?.contiguous()?; let scores=qi.matmul(&ki.t()?.contiguous()?)? .affine(1.0/(c.head_dim as f64).sqrt(),0.)? .broadcast_add(mask)?; let probs=ops::softmax(&scores,1)?; heads.push(probs.matmul(&vi)?); } // Each head is [time,head_dim]. Horizontal concat recovers Q projection width. let joined=CTensor::cat(&heads,1)?; self.linear(&joined,&format!("{prefix}self_attn.o_proj.weight"))? .affine(c.attention_out_multiplier as f64,0.) } fn mamba(&self, x:&CTensor,prefix:&str,n:usize)->Result{ let c=&self.config; let md=c.mamba_dim; let cd=md+2*c.groups*c.state; let hd=md/c.mamba_heads; // All tokens projected at once; mup factors are applied to the correct // [gate, X, B, C, dt] in_proj sections, as in Falcon-H1. let proj=self.linear(x,&format!("{prefix}mamba.in_proj.weight"))? .broadcast_mul(&self.mup)?; let gate=proj.narrow(1,0,md)?; let conv_in=proj.narrow(1,md,cd)?; let dt=proj.narrow(1,md+cd,c.mamba_heads)?; let conv_w=self.w(&format!("{prefix}mamba.conv1d.weight")) .reshape((cd,c.conv))?; let conv_bias=self.w(&format!("{prefix}mamba.conv1d.bias")); // Depthwise causal Conv1d, vectorized across the entire time dimension. let zeros=CTensor::zeros((c.conv-1,cd),DType::F32,&self.device)?; let padded=CTensor::cat(&[zeros,conv_in],0)?; let mut conv=CTensor::zeros((n,cd),DType::F32,&self.device)?; for kernel in 0..c.conv { let frame=padded.narrow(0,kernel,n)?; let coeff=conv_w.narrow(1,kernel,1)?.transpose(0,1)?; conv=conv.broadcast_add(&frame.broadcast_mul(&coeff)?)?; } let conv=ops::silu(&conv.broadcast_add(conv_bias)?)?; let xx=conv.narrow(1,0,md)?.reshape((n,c.mamba_heads,hd))?; let bb=conv.narrow(1,md,c.groups*c.state)?.reshape((n,c.groups,c.state))?; let cc=conv.narrow(1,md+c.groups*c.state,c.groups*c.state)?.reshape((n,c.groups,c.state))?; let dt_bias=self.w(&format!("{prefix}mamba.dt_bias")); let alog=self.w(&format!("{prefix}mamba.A_log")); let dskip=self.w(&format!("{prefix}mamba.D")).reshape((c.mamba_heads,1))?; let neg_a=alog.exp()?.neg()?; let mut state=CTensor::zeros((c.mamba_heads,hd,c.state),DType::F32,&self.device)?; let mut outs=Vec::with_capacity(n); for t in 0..n { let u=xx.narrow(0,t,1)?.squeeze(0)?; // [heads,head_dim] let b=bb.narrow(0,t,1)?.squeeze(0)?.index_select(&self.group_index,0)?; let cv=cc.narrow(0,t,1)?.squeeze(0)?.index_select(&self.group_index,0)?; let dt_t=dt.narrow(0,t,1)?.squeeze(0)?.broadcast_add(dt_bias)?; let step=dt_t.exp()?.affine(1.,1.)?.log()?; // softplus let decay=step.broadcast_mul(&neg_a)?.exp()?.reshape((c.mamba_heads,1,1))?; let step3=step.reshape((c.mamba_heads,1,1))?; let bu=b.unsqueeze(1)?.broadcast_mul(&u.unsqueeze(2)?)?; state=state.broadcast_mul(&decay)?.broadcast_add(&bu.broadcast_mul(&step3)?)?; let y=state.broadcast_mul(&cv.unsqueeze(1)?)?.sum(2)? .broadcast_add(&u.broadcast_mul(&dskip)?)?; let z=gate.narrow(0,t,1)?.reshape((c.mamba_heads,hd))?; let y=y.broadcast_mul(&ops::silu(&z)?)?.reshape((1,md))?; outs.push(y); } let scan=CTensor::cat(&outs,0)?; self.linear(&scan,&format!("{prefix}mamba.out_proj.weight"))? .affine(c.ssm_out_multiplier as f64,0.) } fn forward(&self,ids:&[usize])->Result{ let c=&self.config; let n=ids.len(); let indices=CTensor::from_vec(ids.iter().map(|&i|i as u32).collect::>(),n,&self.device)?; let mut x=self.w("model.embed_tokens.weight").index_select(&indices,0)? .affine(c.embedding_multiplier as f64,0.)?; let (cos,sin)=self.rope_tables(n)?; let mut triangle=vec![0f32;n*n]; for t in 0..n {for j in t+1..n {triangle[t*n+j]=-1.0e9;}} let mask=CTensor::from_vec(triangle,(n,n),&self.device)?; for layer in 0..c.layers { let p=format!("model.layers.{layer}."); let h=self.norm(&x,&format!("{p}input_layernorm.weight"))?; let attention=self.attention(&h,&p,n,&cos,&sin,&mask)?; let ssm=self.mamba(&h,&p,n)?; x=x.broadcast_add(&attention)?.broadcast_add(&ssm)?; let ff=self.norm(&x,&format!("{p}pre_ff_layernorm.weight"))?; let up=self.linear(&ff,&format!("{p}feed_forward.up_proj.weight"))?; let gate=self.linear(&ff,&format!("{p}feed_forward.gate_proj.weight"))? .affine(c.mlp_multipliers[0] as f64,0.)?; let activated=ops::silu(&gate)?.broadcast_mul(&up)?; let projected=self.linear(&activated,&format!("{p}feed_forward.down_proj.weight"))? .affine(c.mlp_multipliers[1] as f64,0.)?; x=x.broadcast_add(&projected)?; } let last=x.narrow(0,n-1,1)?; let h=self.norm(&last,"model.final_layernorm.weight")?; self.linear(&h,"lm_head.weight")?.affine(c.lm_head_multiplier as f64,0.) } pub fn logits(&self,ids:&[usize])->std::result::Result,String>{ if ids.is_empty() || ids.len()>2048 {return Err("input length must be 1..=2048".into());} if ids.iter().any(|&id| id>=self.config.vocab) {return Err("token id outside vocabulary".into());} self.forward(ids).and_then(|t|t.squeeze(0)?.to_vec1::()).map_err(|e|e.to_string()) } pub fn generate(&self,ids:&[usize],count:usize)->std::result::Result,String>{ if count>64 || ids.len()+count>2048 {return Err("generation exceeds limits".into())} let mut result=ids.to_vec(); for _ in 0..count { let logits=self.logits(&result)?; let next=logits.iter().enumerate().max_by(|a,b|a.1.total_cmp(b.1)) .ok_or("empty vocabulary")?.0; result.push(next); } Ok(result) } } #[cfg(test)] mod tests { use super::*; use crate::{synthetic_weights,Model}; #[test] fn small_cpu_candle_matches_reference() { let c=Config::demo();let w=synthetic_weights(&c); let reference=Model::new(c.clone(),w.clone()).unwrap(); let candle=CandleModel::new(c,w,Device::Cpu).unwrap(); let a=reference.logits(&[1,2,3]).unwrap(); let b=candle.logits(&[1,2,3]).unwrap(); let max_diff=a.iter().zip(&b).map(|(x,y)|(x-y).abs()).fold(0f32,f32::max); assert!(max_diff < 1e-3,"max difference {max_diff}"); } #[test] fn official_05b_shape_validation() { assert!(Config::falcon_h1_05b().validate().is_ok()); } }