Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

12.1 KB
Raw Blame
use derive_more::Debug;
use thiserror::Error;

use crate::{
    backends::common::{
        Backend, Buffer, BufferRef, CommandBuffer, CommandBufferEncoding, Context, Kernels,
        kernel::{ShortConvDecodeKernel, ShortConvPackKernel, ShortConvPrefillKernel, ShortConvTrieKernel},
    },
    config::token_mixer::short_conv::ShortConvConfig,
    data_type::DataType,
    encodable_block::{
        batch_topology::BatchTopology,
        linear::{Linear, LinearBlockError},
        mixer::{Mixer, MixerEncodeError, MixerState, attention::rope::PrecalculatedRoPE},
    },
    safetensors::{ParameterLoaderError, ParameterTree},
    utils::{maybe_mut::MaybeMut, size_for_shape::size_for_shape},
};

enum ShortConvStateSuffixStatus<B: Backend> {
    Flat {
        suffix_length: u32,
    },
    Trie {
        conv_states: B::ScratchBuffer,
    },
}

pub struct ShortConvState<B: Backend> {
    conv_state: B::GlobalGpuBuffer,
    suffix_state: Option<ShortConvStateSuffixStatus<B>>,
    is_empty: bool,
}

impl<B: Backend> MixerState<B> for ShortConvState<B> {
    fn prepare(
        &mut self,
        _context_length: u32,
        _suffix_length: u32,
    ) -> Result<(), B::Error> {
        Ok(())
    }

    fn encode_accept(
        &mut self,
        accepted_indices: &[u32],
        command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
    ) -> Result<(), B::Error> {
        let suffix_state_type =
            self.suffix_state.take().expect("Called short conv state encode accept on a state with nothing to accept");

        let accepted_index = *accepted_indices.last().expect("short conv state attempted to accept zero indicies");

        match suffix_state_type {
            ShortConvStateSuffixStatus::Flat {
                suffix_length,
            } => {
                assert!(accepted_index == suffix_length - 1, "attempted to do a partial flat short conv state accept");
                Ok(())
            },
            ShortConvStateSuffixStatus::Trie {
                conv_states,
            } => {
                let conv_state_size = self.conv_state.size();
                let accepted_offset = accepted_index as usize * conv_state_size;
                command_buffer.encode_copy(
                    conv_states.subrange(accepted_offset..accepted_offset + conv_state_size),
                    &mut self.conv_state,
                );
                Ok(())
            },
        }
    }
}

pub struct ShortConv<B: Backend> {
    hidden_dim: u32,
    data_type: DataType,
    kernel_size: u32,
    in_projection: Box<dyn Linear<B>>,
    out_projection: Box<dyn Linear<B>>,
    short_conv_pack: <B::Kernels as Kernels>::ShortConvPackKernel,
    short_conv_prefill: <B::Kernels as Kernels>::ShortConvPrefillKernel,
    short_conv_decode: <B::Kernels as Kernels>::ShortConvDecodeKernel,
    short_conv_trie: <B::Kernels as Kernels>::ShortConvTrieKernel,
    conv_weight: B::GlobalGpuBuffer,
    conv_bias: Option<B::GlobalGpuBuffer>,
}

#[derive(Debug, Error)]
pub enum ShortConvNewError<B: Backend> {
    #[error("Backend error: {0}")]
    Backend(#[source] B::Error),
    #[error("Parameter loader error: {0}")]
    ParameterLoader(#[from] ParameterLoaderError<B>),
    #[error("Linear error: {0}")]
    Linear(#[from] LinearBlockError<B>),
    #[error("Unsupported configuration: {0}")]
    UnsupportedConfiguration(String),
}

impl<B: Backend> ShortConv<B> {
    pub async fn new(
        hidden_dim: u32,
        data_type: DataType,
        config: &ShortConvConfig,
        parameter_tree: &ParameterTree<'_, B>,
        context: &B::Context,
    ) -> Result<(Self, Option<B::GlobalGpuBuffer>), ShortConvNewError<B>> {
        let kernel_size = config.kernel_size;
        if kernel_size < 2 {
            return Err(ShortConvNewError::UnsupportedConfiguration(format!(
                "kernel_size must be >= 2, got {}",
                kernel_size
            )));
        }

        let (in_projection, in_projection_input_hadamard_factors) = <dyn Linear<B>>::new_with_input_rht(
            hidden_dim,
            hidden_dim * 3,
            data_type,
            false,
            &parameter_tree.subtree("in_projection"),
            context,
        )
        .await?;

        let out_projection = <dyn Linear<B>>::new(
            hidden_dim,
            hidden_dim,
            data_type,
            false,
            &parameter_tree.subtree("out_projection"),
            context,
        )
        .await?;

        let conv_tree = parameter_tree.subtree("conv");

        let conv_data_type = DataType::F32;
        let conv_weight = conv_tree.read_buffer("weights", &[hidden_dim, kernel_size], conv_data_type).await?;

        let has_bias = config.conv_config.has_biases;
        let conv_bias = if has_bias {
            Some(conv_tree.read_buffer("biases", &[hidden_dim], conv_data_type).await?)
        } else {
            None
        };

        let short_conv_pack = <B::Kernels as Kernels>::ShortConvPackKernel::new(context, data_type)
            .map_err(ShortConvNewError::Backend)?;
        let short_conv_prefill =
            <B::Kernels as Kernels>::ShortConvPrefillKernel::new(context, data_type, conv_data_type, has_bias)
                .map_err(ShortConvNewError::Backend)?;
        let short_conv_decode =
            <B::Kernels as Kernels>::ShortConvDecodeKernel::new(context, data_type, conv_data_type, has_bias, true)
                .map_err(ShortConvNewError::Backend)?;
        let short_conv_trie =
            <B::Kernels as Kernels>::ShortConvTrieKernel::new(context, data_type, conv_data_type, has_bias)
                .map_err(ShortConvNewError::Backend)?;

        Ok((
            Self {
                hidden_dim,
                data_type,
                kernel_size,
                in_projection,
                out_projection,
                short_conv_pack,
                short_conv_prefill,
                short_conv_decode,
                short_conv_trie,
                conv_weight,
                conv_bias,
            },
            in_projection_input_hadamard_factors,
        ))
    }

    fn encode_decode_conv(
        &self,
        in_projected: impl BufferRef<Backend = B>,
        state: &mut ShortConvState<B>,
        command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
    ) -> Result<B::ScratchBuffer, B::Error> {
        let mut conv_output = command_buffer.allocate_scratch_for_shape(&[self.hidden_dim], self.data_type)?;
        self.short_conv_decode.encode(
            in_projected,
            &self.conv_weight,
            self.conv_bias.as_ref(),
            None::<&B::GlobalGpuBuffer>,
            &mut conv_output,
            &mut state.conv_state,
            1,
            self.kernel_size,
            self.hidden_dim * 3,
            self.kernel_size - 1,
            self.hidden_dim,
            command_buffer,
        );
        Ok(conv_output)
    }

    fn encode_prefill_conv(
        &self,
        in_projected: impl BufferRef<Backend = B>,
        batch_dim: u32,
        state: &mut ShortConvState<B>,
        command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
    ) -> Result<B::ScratchBuffer, B::Error> {
        let state_stride = self.kernel_size - 1;
        let padded_rows = state_stride + batch_dim;

        let mut padded = command_buffer.allocate_scratch_for_shape(&[padded_rows, self.hidden_dim], self.data_type)?;
        self.short_conv_pack.encode(
            &state.conv_state,
            in_projected,
            &mut padded,
            state_stride,
            batch_dim,
            self.hidden_dim * 3,
            self.hidden_dim,
            command_buffer,
        );

        let mut conv_output =
            command_buffer.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim], self.data_type)?;
        self.short_conv_prefill.encode(
            &padded,
            in_projected,
            &self.conv_weight,
            self.conv_bias.as_ref(),
            &mut conv_output,
            &mut state.conv_state,
            batch_dim,
            self.kernel_size,
            self.hidden_dim * 3,
            state_stride,
            self.hidden_dim,
            command_buffer,
        );
        Ok(conv_output)
    }

    fn encode_trie_conv(
        &self,
        in_projected: impl BufferRef<Backend = B>,
        token_parents: impl BufferRef<Backend = B>,
        batch_dim: u32,
        state: &mut ShortConvState<B>,
        command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
    ) -> Result<(B::ScratchBuffer, B::ScratchBuffer), B::Error> {
        let mut conv_output =
            command_buffer.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim], self.data_type)?;
        let mut conv_states = command_buffer
            .allocate_scratch_for_shape(&[batch_dim, self.kernel_size - 1, self.hidden_dim], self.data_type)?;
        self.short_conv_trie.encode(
            in_projected,
            &self.conv_weight,
            self.conv_bias.as_ref(),
            &state.conv_state,
            token_parents,
            &mut conv_output,
            &mut conv_states,
            batch_dim,
            self.kernel_size,
            self.hidden_dim * 3,
            self.kernel_size - 1,
            self.hidden_dim,
            command_buffer,
        );
        Ok((conv_output, conv_states))
    }
}

impl<B: Backend> Mixer<B> for ShortConv<B> {
    fn speculation_supported(&self) -> bool {
        true
    }

    fn max_context_length(&self) -> Option<u32> {
        None
    }

    fn create_empty_state(
        &self,
        _max_context_length: Option<u32>,
        context: &B::Context,
    ) -> Result<Box<dyn MixerState<B>>, B::Error> {
        let conv_state =
            context.create_buffer_gpu(size_for_shape(&[self.kernel_size - 1, self.hidden_dim], self.data_type))?;

        Ok(Box::new(ShortConvState {
            conv_state,
            suffix_state: None,
            is_empty: true,
        }))
    }

    fn encode(
        &self,
        hidden: B::ScratchBuffer,
        precalculated_rope: Option<&PrecalculatedRoPE<B>>,
        batch_dim: &BatchTopology,
        state: Option<MaybeMut<dyn MixerState<B>>>,
        command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
    ) -> Result<B::ScratchBuffer, MixerEncodeError<B>> {
        let command_buffer = &mut *command_buffer.debug_group("short conv");

        assert!(precalculated_rope.is_none(), "unexpected rope for short conv mixer");

        let state = state.expect("short conv requires state");
        let state = state.downcast::<ShortConvState<B>>().expect("incorrect type of short conv state");
        let MaybeMut::Mut(state) = state else {
            panic!("incorrect state access for short conv state");
        };

        assert!(state.suffix_state.is_none(), "short conv called with state with unaccepted tokens");

        if state.is_empty {
            command_buffer.encode_fill(&mut state.conv_state, 0);
            state.is_empty = false;
        }

        let in_projected = self.in_projection.encode(hidden, batch_dim.size(), command_buffer)?;

        let conv_output = if batch_dim.full_accept() {
            let conv_output = if batch_dim.size() == 1 {
                self.encode_decode_conv(&in_projected, state, command_buffer).map_err(MixerEncodeError::Backend)?
            } else {
                self.encode_prefill_conv(&in_projected, batch_dim.size(), state, command_buffer)
                    .map_err(MixerEncodeError::Backend)?
            };
            state.suffix_state = Some(ShortConvStateSuffixStatus::Flat {
                suffix_length: batch_dim.size(),
            });
            conv_output
        } else {
            let token_parents =
                command_buffer.allocate_constant_from_slice(batch_dim.parents()).map_err(MixerEncodeError::Backend)?;
            let (conv_output, conv_states) = self
                .encode_trie_conv(&in_projected, &token_parents, batch_dim.size(), state, command_buffer)
                .map_err(MixerEncodeError::Backend)?;
            state.suffix_state = Some(ShortConvStateSuffixStatus::Trie {
                conv_states,
            });
            conv_output
        };

        let output = self.out_projection.encode(conv_output, batch_dim.size(), command_buffer)?;

        Ok(output)
    }
}