Download src/hybrid.rs from hongcoding/perch-ultrafast: direct link, hf CLI and curl.
- Browser
- Download file 9.73 kB
-
https://huggingface.co/hongcoding/perch-ultrafast/resolve/main/src/hybrid.rs
- Command line
-
hf download hf://hongcoding/perch-ultrafast/src/hybrid.rs
-
curl -L -o hybrid.rs https://huggingface.co/hongcoding/perch-ultrafast/resolve/main/src/hybrid.rs
9.73 kB
| //! 混合流(Hybrid Streaming):本机小模型先出草稿,云端大模型无缝接棒。 | |
| //! | |
| //! # 为什么 | |
| //! | |
| //! 云端大模型的**首 token 延迟**通常在 0.5~2 秒(网络 + 排队 + 预填充)。 | |
| //! 本机小模型(如 0.6B)热身后首 token 只要 0.04~0.2 秒。 | |
| //! | |
| //! 混合流让用户**立刻有东西可读**:本机先答,云端一到就接棒—— | |
| //! 用户看到的首字延迟 = 本机延迟,最终质量 = 云端质量。 | |
| //! | |
| //! # 时序 | |
| //! | |
| //! ```text | |
| //! t=0ms 同时开两条流(本机 + 云端) | |
| //! t=80ms 本机首字到达 → 用户立刻看到草稿 | |
| //! t=900ms 云端首字到达 → 发 Replaced(前端清空草稿)→ 换成云端正文 | |
| //! t=3000ms 云端结束 → Done | |
| //! ``` | |
| //! | |
| //! # 降级 | |
| //! | |
| //! - 云端建流失败 → 纯本地跑完(有草稿就继续用) | |
| //! - 本机建流失败 → 纯云端跑完(行为等同没用混合流) | |
| //! - 云端中途出错 → 保留本地草稿、按完成收尾(不把草稿变成错误) | |
| use std::sync::Arc; | |
| use std::time::Duration; | |
| use futures::StreamExt; | |
| use tokio_util::sync::CancellationToken; | |
| use crate::types::{ChatRequest, Provider, ProviderStream, StreamChunk}; | |
| /// 混合流配置。 | |
| pub struct HybridConfig { | |
| /// 等本机草稿流建立的上限。超时就先不管草稿(云端照跑)。 | |
| pub fast_open_timeout: Duration, | |
| } | |
| impl Default for HybridConfig { | |
| fn default() -> Self { | |
| Self { | |
| fast_open_timeout: Duration::from_millis(50), | |
| } | |
| } | |
| } | |
| /// 混合流跑完后的结果。 | |
| pub struct HybridResult { | |
| /// 最终正文(接棒后是云端内容;未接棒则是本地草稿)。 | |
| pub content: String, | |
| /// 是否真的发生了"云端接棒"。 | |
| pub used_cloud: bool, | |
| /// 是否正常结束(false = 被取消 / 异常)。 | |
| pub finished: bool, | |
| } | |
| /// 跑一次混合流。所有分片通过 `emit` 回调下发给调用方(接 WebSocket / IPC / SSE)。 | |
| /// | |
| /// - `fast`:本机快模型(预热过,首字 ~0.08s) | |
| /// - `slow`:云端慢模型(质量担当) | |
| /// - `fast_request`:通常复用 `slow_request` 的消息上下文,但关思考 + 小 max_tokens | |
| /// | |
| /// 返回时流已结束(正常 Done / 出错 / 取消)。 | |
| pub async fn run_hybrid<F>( | |
| fast: Arc<dyn Provider>, | |
| slow: Arc<dyn Provider>, | |
| fast_request: ChatRequest, | |
| slow_request: ChatRequest, | |
| cancel: CancellationToken, | |
| config: HybridConfig, | |
| mut emit: F, | |
| ) -> HybridResult | |
| where | |
| F: FnMut(StreamChunk), | |
| { | |
| let mut content = String::new(); | |
| let mut used_cloud = false; | |
| // ── 同时开两条流 ──────────────────────────────────────────────── | |
| // 云端正式连接**立刻**发起(本机草稿绝不能推迟它); | |
| // 本机草稿给一个短超时,太慢就当没有草稿。 | |
| let fast_cancel = cancel.clone(); | |
| let slow_cancel = cancel.clone(); | |
| let fast_open = async move { | |
| tokio::time::timeout( | |
| config.fast_open_timeout, | |
| fast.chat_stream(fast_request, fast_cancel), | |
| ) | |
| .await | |
| .unwrap_or_else(|_| Err("draft not ready".to_string())) | |
| }; | |
| let (fast_res, slow_res) = tokio::select! { | |
| biased; | |
| _ = cancel.cancelled() => { | |
| return HybridResult { content, used_cloud, finished: false }; | |
| } | |
| results = async { tokio::join!(fast_open, slow.chat_stream(slow_request, slow_cancel)) } => results, | |
| }; | |
| let mut fast_stream: Option<ProviderStream> = fast_res.ok(); | |
| let mut slow_stream = match slow_res { | |
| Ok(s) => s, | |
| Err(message) => { | |
| // 云端建流失败 → 退回纯本地(有草稿就继续跑完,没有就报错) | |
| if let Some(mut fast) = fast_stream.take() { | |
| while let Some(chunk) = fast.next().await { | |
| match chunk { | |
| StreamChunk::Delta { text } => { | |
| content.push_str(&text); | |
| emit(StreamChunk::Delta { text }); | |
| } | |
| StreamChunk::Done { .. } => { | |
| emit(chunk); | |
| return HybridResult { content, used_cloud, finished: true }; | |
| } | |
| StreamChunk::Error { message } => { | |
| emit(StreamChunk::Error { message }); | |
| return HybridResult { content, used_cloud, finished: false }; | |
| } | |
| other => emit(other), | |
| } | |
| } | |
| return HybridResult { content, used_cloud, finished: true }; | |
| } | |
| emit(StreamChunk::Error { message }); | |
| return HybridResult { content, used_cloud, finished: false }; | |
| } | |
| }; | |
| // ── 阶段 1:本机先答,云端一到就接棒 ─────────────────────────── | |
| loop { | |
| if cancel.is_cancelled() { | |
| return HybridResult { content, used_cloud, finished: false }; | |
| } | |
| if used_cloud { | |
| // ── 阶段 2:只消费云端 ────────────────────────────────── | |
| match slow_stream.next().await { | |
| Some(StreamChunk::Delta { text }) => { | |
| content.push_str(&text); | |
| emit(StreamChunk::Delta { text }); | |
| } | |
| Some(StreamChunk::Done { .. }) => { | |
| emit(StreamChunk::Done { | |
| prompt_tokens: None, | |
| completion_tokens: None, | |
| eval_ms: None, | |
| cached_tokens: None, | |
| }); | |
| return HybridResult { content, used_cloud, finished: true }; | |
| } | |
| Some(StreamChunk::Error { message }) => { | |
| emit(StreamChunk::Error { message }); | |
| return HybridResult { content, used_cloud, finished: false }; | |
| } | |
| Some(other) => emit(other), | |
| None => { | |
| // 云端流提前结束(没发 Done):按完成处理 | |
| return HybridResult { content, used_cloud, finished: true }; | |
| } | |
| } | |
| } else { | |
| tokio::select! { | |
| _ = cancel.cancelled() => { | |
| return HybridResult { content, used_cloud, finished: false }; | |
| } | |
| f = next_opt(&mut fast_stream) => { | |
| match f { | |
| Some(StreamChunk::Delta { text }) => { | |
| content.push_str(&text); | |
| emit(StreamChunk::Delta { text }); | |
| } | |
| Some(_) => {} | |
| None => { fast_stream = None; } | |
| } | |
| } | |
| s = slow_stream.next() => { | |
| match s { | |
| Some(StreamChunk::Delta { text }) => { | |
| // ── 接棒:清草稿 + 发 Replaced + 用云端继续 ── | |
| used_cloud = true; | |
| content.clear(); | |
| emit(StreamChunk::Replaced { | |
| message: "云端模型已接棒".to_string(), | |
| }); | |
| content.push_str(&text); | |
| emit(StreamChunk::Delta { text }); | |
| } | |
| Some(StreamChunk::Done { | |
| prompt_tokens, | |
| completion_tokens, | |
| eval_ms, | |
| cached_tokens, | |
| }) => { | |
| // 云端没有正文就结束(本地草稿作为结果) | |
| emit(StreamChunk::Done { | |
| prompt_tokens, | |
| completion_tokens, | |
| eval_ms, | |
| cached_tokens, | |
| }); | |
| return HybridResult { content, used_cloud, finished: true }; | |
| } | |
| Some(StreamChunk::Error { message }) => { | |
| // 云端失败:本地草稿保留,按完成收尾 | |
| if content.trim().is_empty() { | |
| emit(StreamChunk::Error { message }); | |
| return HybridResult { content, used_cloud, finished: false }; | |
| } | |
| return HybridResult { content, used_cloud, finished: true }; | |
| } | |
| Some(other) => emit(other), | |
| None => { | |
| // 云端流提前结束:草稿作为结果 | |
| return HybridResult { content, used_cloud, finished: true }; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| /// 取流的下一个元素;流已经关闭(None)时**永远挂起**, | |
| /// 这样 `select!` 里另一条流可以继续被轮询。 | |
| async fn next_opt(stream: &mut Option<ProviderStream>) -> Option<StreamChunk> { | |
| match stream.as_mut() { | |
| Some(s) => s.next().await, | |
| None => std::future::pending().await, | |
| } | |
| } | |