hf2q 0.1.33

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
//! Actual request-local decoder work, independent of model-wide route selection.
//!
//! Count a forward/verify operation once, where it produces accepted tokens.
//! Draining already verified output is not another operation. The seed sampled
//! from prefill logits is separate: it does not require a decode forward.

use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};

static NEXT_REQUEST: AtomicU64 = AtomicU64::new(1);

#[derive(Clone, Copy, Debug)]
#[repr(usize)]
pub(in crate::serve::api) enum DecodeWorkRoute {
    Target,
    Mtp,
    History,
    DFlash2,
}

#[derive(Clone, Copy, Debug)]
#[repr(usize)]
pub(in crate::serve::api) enum DFlash2Refusal {
    NotProvisioned,
    NoJointConfiguration,
    ActiveTargetCapture,
    NotDecodePhase,
    GenerationUnavailable,
    ClientClosed,
    AnchorTransaction,
    PendingVerifiedOutput,
    TokenLimit,
    SeedMissing,
    TargetCursorMismatch,
    DrafterCursorMismatch,
    UnsupportedSemantics,
    Vision,
    KvGraft,
    JointReadiness,
}

impl DFlash2Refusal {
    const ALL: [Self; 16] = [
        Self::NotProvisioned,
        Self::NoJointConfiguration,
        Self::ActiveTargetCapture,
        Self::NotDecodePhase,
        Self::GenerationUnavailable,
        Self::ClientClosed,
        Self::AnchorTransaction,
        Self::PendingVerifiedOutput,
        Self::TokenLimit,
        Self::SeedMissing,
        Self::TargetCursorMismatch,
        Self::DrafterCursorMismatch,
        Self::UnsupportedSemantics,
        Self::Vision,
        Self::KvGraft,
        Self::JointReadiness,
    ];

    const fn label(self) -> &'static str {
        match self {
            Self::NotProvisioned => "not_provisioned",
            Self::NoJointConfiguration => "no_joint_configuration",
            Self::ActiveTargetCapture => "active_target_capture",
            Self::NotDecodePhase => "not_decode_phase",
            Self::GenerationUnavailable => "generation_unavailable",
            Self::ClientClosed => "client_closed",
            Self::AnchorTransaction => "anchor_transaction",
            Self::PendingVerifiedOutput => "pending_verified_output",
            Self::TokenLimit => "token_limit",
            Self::SeedMissing => "seed_missing",
            Self::TargetCursorMismatch => "target_cursor_mismatch",
            Self::DrafterCursorMismatch => "drafter_cursor_mismatch",
            Self::UnsupportedSemantics => "unsupported_semantics",
            Self::Vision => "vision",
            Self::KvGraft => "kv_graft",
            Self::JointReadiness => "joint_readiness",
        }
    }
}

#[derive(Debug, Default)]
struct Work {
    rounds: usize,
    accepted_tokens: usize,
}

#[derive(Debug)]
pub(in crate::serve::api) struct DecodeRouteEvidence {
    request_sequence: u64,
    dflash2_provisioned: bool,
    prefill_seed_tokens: usize,
    work: [Work; 4],
    refusals: [usize; 16],
}

impl DecodeRouteEvidence {
    pub(in crate::serve::api) fn new(dflash2_provisioned: bool) -> Self {
        Self {
            request_sequence: NEXT_REQUEST.fetch_add(1, Ordering::Relaxed),
            dflash2_provisioned,
            prefill_seed_tokens: 0,
            work: std::array::from_fn(|_| Work::default()),
            refusals: [0; 16],
        }
    }

    pub(in crate::serve::api) fn record_seed_tokens(&mut self, tokens: usize) {
        self.prefill_seed_tokens += tokens;
    }

    pub(in crate::serve::api) fn record_work(
        &mut self,
        route: DecodeWorkRoute,
        accepted_tokens: usize,
    ) {
        let work = &mut self.work[route as usize];
        work.rounds += 1;
        work.accepted_tokens += accepted_tokens;
    }

    pub(in crate::serve::api) fn record_refusal(&mut self, reason: DFlash2Refusal) {
        self.refusals[reason as usize] += 1;
    }

    pub(in crate::serve::api) fn emit_summary(
        &self,
        slot: u32,
        cached_tokens: usize,
        completion_tokens: usize,
    ) {
        let target = &self.work[DecodeWorkRoute::Target as usize];
        let mtp = &self.work[DecodeWorkRoute::Mtp as usize];
        let history = &self.work[DecodeWorkRoute::History as usize];
        let dflash2 = &self.work[DecodeWorkRoute::DFlash2 as usize];
        tracing::info!(
            target: "hf2q::serve::api::engine_qwen35::progress",
            schema = "hf2q.request-decoder-work.v1",
            process_pid = std::process::id(),
            request_sequence = self.request_sequence,
            slot,
            cached_tokens,
            completion_tokens,
            prefill_seed_tokens = self.prefill_seed_tokens,
            dflash2_provisioned = self.dflash2_provisioned,
            dflash2_engaged = dflash2.rounds != 0,
            target_rounds = target.rounds,
            target_accepted_tokens = target.accepted_tokens,
            mtp_rounds = mtp.rounds,
            mtp_accepted_tokens = mtp.accepted_tokens,
            history_rounds = history.rounds,
            history_accepted_tokens = history.accepted_tokens,
            dflash2_rounds = dflash2.rounds,
            dflash2_accepted_tokens = dflash2.accepted_tokens,
            dflash2_refusals = ?RefusalCounts(&self.refusals),
            "Qwen35 request decoder work"
        );
    }
}

struct RefusalCounts<'a>(&'a [usize; 16]);

impl fmt::Debug for RefusalCounts<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut map = formatter.debug_map();
        for reason in DFlash2Refusal::ALL {
            let count = self.0[reason as usize];
            if count != 0 {
                map.entry(&reason.label(), &count);
            }
        }
        map.finish()
    }
}