Instructions to use Gavin-chen/Qwen-Compress with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Gavin-chen/Qwen-Compress with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Gavin-chen/Qwen-Compress", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload 2 files
Browse files- franken_qwen27B_compressoronly_checkpoint.pt +3 -0
- server.py +434 -0
franken_qwen27B_compressoronly_checkpoint.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:549d46d9d6a31e5e9f061eeda38dd8b6b9b04a1e0306f1e29018058b41667a16
|
| 3 |
+
size 175301
|
server.py
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import uvicorn
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
import uuid
|
| 9 |
+
import json
|
| 10 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 11 |
+
from fastapi.responses import JSONResponse
|
| 12 |
+
from fastapi.responses import StreamingResponse
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
+
from pydantic import BaseModel, Field, ConfigDict
|
| 15 |
+
from typing import List, Optional, Union, Dict, Any
|
| 16 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
|
| 17 |
+
from transformers import BitsAndBytesConfig
|
| 18 |
+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 19 |
+
from torch.utils.checkpoint import checkpoint
|
| 20 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 21 |
+
import asyncio
|
| 22 |
+
# ==========================================
|
| 23 |
+
# 1. 初始化 FastAPI App 與 跨域(CORS) 設定
|
| 24 |
+
# ==========================================
|
| 25 |
+
app = FastAPI(title="OpenAI-Compatible FrankenQwen Server", version="1.0")
|
| 26 |
+
|
| 27 |
+
# 開啟 CORS,讓前端 UI (如 Open WebUI) 可以順利連線
|
| 28 |
+
app.add_middleware(
|
| 29 |
+
CORSMiddleware,
|
| 30 |
+
allow_origins=["*"],
|
| 31 |
+
allow_credentials=True,
|
| 32 |
+
allow_methods=["*"],
|
| 33 |
+
allow_headers=["*"],
|
| 34 |
+
)
|
| 35 |
+
MAX_CONCURRENT_REQUESTS = 4
|
| 36 |
+
gpu_semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
|
| 37 |
+
def get_vram_status():
|
| 38 |
+
import torch
|
| 39 |
+
if not torch.cuda.is_available():
|
| 40 |
+
return {"status": "CUDA 不可用"}
|
| 41 |
+
|
| 42 |
+
# 轉換為 GiB (除以 1024^3)
|
| 43 |
+
allocated = torch.cuda.memory_allocated() / (1024 ** 3)
|
| 44 |
+
reserved = torch.cuda.memory_reserved() / (1024 ** 3)
|
| 45 |
+
peak = torch.cuda.max_memory_allocated() / (1024 ** 3)
|
| 46 |
+
|
| 47 |
+
return {
|
| 48 |
+
"current_tensor_used_gib": round(allocated, 2),
|
| 49 |
+
"pytorch_reserved_gib": round(reserved, 2),
|
| 50 |
+
"peak_vram_used_gib": round(peak, 2)
|
| 51 |
+
}
|
| 52 |
+
# ==========================================
|
| 53 |
+
# 2. 原始模型組件與邏輯 (保持不變)
|
| 54 |
+
# ==========================================
|
| 55 |
+
class HiddenStateCompressor(nn.Module):
|
| 56 |
+
def __init__(self, dim, ratio=4):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.ratio = ratio
|
| 59 |
+
self.wgate = nn.Linear(dim, 1, bias=False)
|
| 60 |
+
self.ape = nn.Parameter(torch.empty(ratio, 1))
|
| 61 |
+
nn.init.normal_(self.ape, std=0.02)
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
B, L, D = x.shape
|
| 65 |
+
assert L % self.ratio == 0, "輸入長度必須是壓縮倍率的整數倍"
|
| 66 |
+
orig_dtype = x.dtype
|
| 67 |
+
target_dtype = self.wgate.weight.dtype
|
| 68 |
+
x_reshaped = x.view(B, L // self.ratio, self.ratio, D).to(target_dtype)
|
| 69 |
+
scores = self.wgate(x_reshaped) + self.ape.view(1, 1, self.ratio, 1)
|
| 70 |
+
scores_fp32 = scores.to(torch.float32)
|
| 71 |
+
scores_probs = F.softmax(scores_fp32, dim=2).to(target_dtype)
|
| 72 |
+
compressed_x = (x_reshaped * scores_probs).sum(dim=2)
|
| 73 |
+
return compressed_x.to(orig_dtype)
|
| 74 |
+
|
| 75 |
+
def get_custom_qwen_forward(compressor_module, window_size=128, ratio=4):
|
| 76 |
+
from collections.abc import Callable
|
| 77 |
+
from transformers.models.qwen3_5.modeling_qwen3_5 import ALL_ATTENTION_FUNCTIONS, apply_rotary_pos_emb, eager_attention_forward, FlashAttentionKwargs
|
| 78 |
+
from transformers.processing_utils import Unpack
|
| 79 |
+
from transformers.cache_utils import Cache
|
| 80 |
+
|
| 81 |
+
def forward2(
|
| 82 |
+
self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 83 |
+
attention_mask: torch.Tensor | None, past_key_values: Cache | None = None, **kwargs: Unpack[FlashAttentionKwargs],
|
| 84 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 85 |
+
cos, sin = position_embeddings
|
| 86 |
+
bsz, q_len, _ = hidden_states.size()
|
| 87 |
+
input_shape = hidden_states.shape[:-1]
|
| 88 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 89 |
+
|
| 90 |
+
hidden_states = hidden_states.contiguous()
|
| 91 |
+
query_states, gate = torch.chunk(
|
| 92 |
+
self.q_proj(hidden_states).view(*input_shape, -1, self.head_dim * 2), 2, dim=-1
|
| 93 |
+
)
|
| 94 |
+
gate = gate.contiguous().reshape(*input_shape, -1)
|
| 95 |
+
query_states = self.q_norm(query_states.contiguous().view(hidden_shape)).transpose(1, 2)
|
| 96 |
+
key_states, value_states = None, None
|
| 97 |
+
do_compress = getattr(self, "compress_enabled", True)
|
| 98 |
+
|
| 99 |
+
if do_compress:
|
| 100 |
+
if q_len > 1: # Prefill
|
| 101 |
+
window = min(window_size, q_len)
|
| 102 |
+
global_len = q_len - window
|
| 103 |
+
cutoff = global_len - (global_len % ratio)
|
| 104 |
+
compressed = compressor_module(hidden_states[:, :cutoff, :]) if cutoff > 0 else hidden_states[:, :0, :]
|
| 105 |
+
residual = hidden_states[:, cutoff:global_len, :] if global_len > cutoff else hidden_states[:, :0, :]
|
| 106 |
+
tail = hidden_states[:, global_len:, :]
|
| 107 |
+
kv_hidden = torch.cat([compressed, residual, tail], dim=1).contiguous()
|
| 108 |
+
|
| 109 |
+
compressed_pos = torch.arange(ratio - 1, cutoff, ratio, device=hidden_states.device, dtype=torch.long) if cutoff > 0 else torch.arange(0, device=hidden_states.device, dtype=torch.long)
|
| 110 |
+
residual_pos = torch.arange(cutoff, global_len, device=hidden_states.device, dtype=torch.long)
|
| 111 |
+
tail_pos = torch.arange(global_len, q_len, device=hidden_states.device, dtype=torch.long)
|
| 112 |
+
kv_positions = torch.cat([compressed_pos, residual_pos, tail_pos], dim=0)
|
| 113 |
+
kv_seq_len = kv_positions.size(0)
|
| 114 |
+
|
| 115 |
+
q_pos = torch.arange(q_len, device=hidden_states.device).view(q_len, 1)
|
| 116 |
+
k_pos = kv_positions.view(1, kv_seq_len)
|
| 117 |
+
custom_causal_mask = (q_pos >= k_pos)
|
| 118 |
+
additive_mask = torch.zeros((q_len, kv_seq_len), dtype=hidden_states.dtype, device=hidden_states.device)
|
| 119 |
+
additive_mask.masked_fill_(~custom_causal_mask, torch.finfo(hidden_states.dtype).min)
|
| 120 |
+
additive_mask = additive_mask.view(1, 1, q_len, kv_seq_len).expand(bsz, 1, q_len, kv_seq_len)
|
| 121 |
+
|
| 122 |
+
attention_mask = (attention_mask[..., kv_positions] + additive_mask) if attention_mask is not None else additive_mask
|
| 123 |
+
kv_hidden_shape = (bsz, kv_seq_len, -1, self.head_dim)
|
| 124 |
+
key_states = self.k_norm(self.k_proj(kv_hidden).view(kv_hidden_shape)).transpose(1, 2).contiguous()
|
| 125 |
+
value_states = self.v_proj(kv_hidden).view(kv_hidden_shape).transpose(1, 2).contiguous()
|
| 126 |
+
|
| 127 |
+
query_states, _ = apply_rotary_pos_emb(query_states, query_states, cos, sin)
|
| 128 |
+
k_cos = cos[:, kv_positions, :] if cos.dim() == 3 else cos[kv_positions, :]
|
| 129 |
+
k_sin = sin[:, kv_positions, :] if sin.dim() == 3 else sin[kv_positions, :]
|
| 130 |
+
_, key_states = apply_rotary_pos_emb(key_states, key_states, k_cos, k_sin)
|
| 131 |
+
if past_key_values is not None:
|
| 132 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 133 |
+
else: # Decode
|
| 134 |
+
new_key = self.k_norm(self.k_proj(hidden_states).view(bsz, 1, -1, self.head_dim)).transpose(1, 2)
|
| 135 |
+
new_value = self.v_proj(hidden_states).view(bsz, 1, -1, self.head_dim).transpose(1, 2)
|
| 136 |
+
query_states, _ = apply_rotary_pos_emb(query_states, query_states, cos, sin)
|
| 137 |
+
_, new_key = apply_rotary_pos_emb(new_key, new_key, cos, sin)
|
| 138 |
+
|
| 139 |
+
target_dtype = hidden_states.dtype
|
| 140 |
+
new_key = new_key.to(target_dtype).contiguous()
|
| 141 |
+
new_value = new_value.to(target_dtype).contiguous()
|
| 142 |
+
|
| 143 |
+
if past_key_values is not None:
|
| 144 |
+
if not hasattr(past_key_values, "uncompressed_buffer_k"):
|
| 145 |
+
past_key_values.uncompressed_buf_h = {}
|
| 146 |
+
past_key_values.uncompressed_buffer_k = {}
|
| 147 |
+
past_key_values.uncompressed_buffer_v = {}
|
| 148 |
+
|
| 149 |
+
layer_idx = self.layer_idx
|
| 150 |
+
buf_k = past_key_values.uncompressed_buffer_k.get(layer_idx, torch.empty((bsz, self.config.num_key_value_heads, 0, self.head_dim), device=new_key.device, dtype=target_dtype))
|
| 151 |
+
buf_v = past_key_values.uncompressed_buffer_v.get(layer_idx, torch.empty((bsz, self.config.num_key_value_heads, 0, self.head_dim), device=new_value.device, dtype=target_dtype))
|
| 152 |
+
buf_h = past_key_values.uncompressed_buf_h.get(layer_idx, torch.empty((bsz, 0, hidden_states.size(-1)), device=hidden_states.device, dtype=hidden_states.dtype))
|
| 153 |
+
|
| 154 |
+
buf_h = torch.cat([buf_h, hidden_states], dim=1)
|
| 155 |
+
buf_k = torch.cat([buf_k, new_key], dim=2)
|
| 156 |
+
buf_v = torch.cat([buf_v, new_value], dim=2)
|
| 157 |
+
|
| 158 |
+
buffer_len = buf_k.shape[2]
|
| 159 |
+
if getattr(self, "compress_enabled", True) and buffer_len >= (window_size + ratio):
|
| 160 |
+
to_compress_h = buf_h[:, :ratio, :]
|
| 161 |
+
compressed_h = compressor_module(to_compress_h)
|
| 162 |
+
compressed_k = self.k_norm(self.k_proj(compressed_h).view(bsz, 1, -1, self.head_dim)).transpose(1, 2)
|
| 163 |
+
compressed_v = self.v_proj(compressed_h).view(bsz, 1, -1, self.head_dim).transpose(1, 2)
|
| 164 |
+
|
| 165 |
+
past_key_values.update(compressed_k, compressed_v, layer_idx)
|
| 166 |
+
buf_h = buf_h[:, ratio:, :]
|
| 167 |
+
buf_k = buf_k[:, :, ratio:, :]
|
| 168 |
+
buf_v = buf_v[:, :, ratio:, :]
|
| 169 |
+
|
| 170 |
+
past_key_values.uncompressed_buffer_k[layer_idx] = buf_k
|
| 171 |
+
past_key_values.uncompressed_buffer_v[layer_idx] = buf_v
|
| 172 |
+
past_key_values.uncompressed_buf_h[layer_idx] = buf_h
|
| 173 |
+
|
| 174 |
+
layer_cache = past_key_values.layers[layer_idx] if hasattr(past_key_values, "layers") else None
|
| 175 |
+
history_k = layer_cache.keys if layer_cache else past_key_values.key_cache[layer_idx]
|
| 176 |
+
history_v = layer_cache.values if layer_cache else past_key_values.value_cache[layer_idx]
|
| 177 |
+
|
| 178 |
+
key_states = torch.cat([history_k, buf_k], dim=2) if history_k is not None and history_k.shape[2] > 0 else buf_k
|
| 179 |
+
value_states = torch.cat([history_v, buf_v], dim=2) if history_v is not None and history_v.shape[2] > 0 else buf_v
|
| 180 |
+
kv_seq_len = past_key_values.get_seq_length(self.layer_idx) + buf_k.shape[2]
|
| 181 |
+
else:
|
| 182 |
+
key_states, value_states = new_key, new_value
|
| 183 |
+
else:
|
| 184 |
+
kv_hidden_shape = (bsz, q_len, -1, self.head_dim)
|
| 185 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(kv_hidden_shape)).transpose(1, 2).contiguous()
|
| 186 |
+
value_states = self.v_proj(hidden_states).view(kv_hidden_shape).transpose(1, 2).contiguous()
|
| 187 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 188 |
+
if past_key_values is not None:
|
| 189 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 190 |
+
kv_seq_len = key_states.shape[2]
|
| 191 |
+
|
| 192 |
+
target_dtype = hidden_states.dtype
|
| 193 |
+
query_states, key_states, value_states = query_states.to(target_dtype).contiguous(), key_states.to(target_dtype).contiguous(), value_states.to(target_dtype).contiguous()
|
| 194 |
+
|
| 195 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(self.config._attn_implementation, eager_attention_forward)
|
| 196 |
+
attn_output, attn_weights = attention_interface(
|
| 197 |
+
self, query_states, key_states, value_states, attention_mask,
|
| 198 |
+
dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs,
|
| 199 |
+
)
|
| 200 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 201 |
+
attn_output = attn_output * torch.sigmoid(gate)
|
| 202 |
+
return self.o_proj(attn_output), attn_weights
|
| 203 |
+
|
| 204 |
+
return forward2
|
| 205 |
+
|
| 206 |
+
def get_chunked_causal_forward(chunk_size=512):
|
| 207 |
+
def custom_causal_forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs):
|
| 208 |
+
outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, **kwargs)
|
| 209 |
+
hidden_states = outputs[0]
|
| 210 |
+
loss, logits = None, None
|
| 211 |
+
|
| 212 |
+
if labels is not None:
|
| 213 |
+
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
| 214 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 215 |
+
seq_len = shift_hidden_states.shape[1]
|
| 216 |
+
total_loss = 0.0
|
| 217 |
+
active_tokens = (shift_labels != -100).sum().clamp(min=1)
|
| 218 |
+
|
| 219 |
+
def compute_chunk_loss(h_chunk, lbl_chunk):
|
| 220 |
+
c_logits = self.lm_head(h_chunk).float()
|
| 221 |
+
return F.cross_entropy(c_logits.reshape(-1, c_logits.size(-1)), lbl_chunk.reshape(-1), reduction='sum')
|
| 222 |
+
|
| 223 |
+
for i in range(0, seq_len, chunk_size):
|
| 224 |
+
end_i = min(i + chunk_size, seq_len)
|
| 225 |
+
c_loss = checkpoint(compute_chunk_loss, shift_hidden_states[:, i:end_i, :], shift_labels[:, i:end_i], use_reentrant=False)
|
| 226 |
+
total_loss += c_loss
|
| 227 |
+
loss = total_loss / active_tokens
|
| 228 |
+
else:
|
| 229 |
+
logits = self.lm_head(hidden_states)
|
| 230 |
+
|
| 231 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
| 232 |
+
return custom_causal_forward
|
| 233 |
+
|
| 234 |
+
def load_custom_checkpoint(model, filepath="/vault/franken_qwen2B_compressor_checkpoint.pt"):
|
| 235 |
+
if not os.path.exists(filepath):
|
| 236 |
+
print(f"⚠️ 找不到權重檔 {filepath}!將使用原始權重。")
|
| 237 |
+
return model
|
| 238 |
+
print(f"\n📂 正在載入客製化權重: {filepath}")
|
| 239 |
+
trainable_state_dict = torch.load(filepath, map_location="cpu", weights_only=True)
|
| 240 |
+
clean_state_dict = { (k[7:] if k.startswith('module.') else k): v for k, v in trainable_state_dict.items() }
|
| 241 |
+
model.load_state_dict(clean_state_dict, strict=False)
|
| 242 |
+
print("✅ 客製化權重完美掛載!")
|
| 243 |
+
return model
|
| 244 |
+
|
| 245 |
+
def build_franken_qwen(qwen_id="Qwen/Qwen3.6-27B", device="cuda"):
|
| 246 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
|
| 247 |
+
qwen_model = AutoModelForCausalLM.from_pretrained(qwen_id, dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config)
|
| 248 |
+
#qwen_model = prepare_model_for_kbit_training(qwen_model)
|
| 249 |
+
|
| 250 |
+
qwen_model.compressors = nn.ModuleList()
|
| 251 |
+
for i, layer in enumerate(qwen_model.model.layers):
|
| 252 |
+
if i % 4 == 3:
|
| 253 |
+
compressor = HiddenStateCompressor(dim=qwen_model.config.hidden_size, ratio=4).to(device, dtype=torch.bfloat16)
|
| 254 |
+
qwen_model.compressors.append(compressor)
|
| 255 |
+
custom_fw = get_custom_qwen_forward(compressor, window_size=128, ratio=4)
|
| 256 |
+
layer.self_attn.forward = custom_fw.__get__(layer.self_attn, type(layer.self_attn))
|
| 257 |
+
|
| 258 |
+
qwen_model.forward = get_chunked_causal_forward(chunk_size=512).__get__(qwen_model, type(qwen_model))
|
| 259 |
+
|
| 260 |
+
for param in qwen_model.parameters(): param.requires_grad = False
|
| 261 |
+
for compressor in qwen_model.compressors:
|
| 262 |
+
for param in compressor.parameters(): param.requires_grad = True
|
| 263 |
+
if qwen_id=="Qwen/Qwen3.6-27B":
|
| 264 |
+
lora_config = LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM")
|
| 265 |
+
qwen_model = get_peft_model(qwen_model, lora_config)
|
| 266 |
+
return load_custom_checkpoint(qwen_model, filepath="./Downloads/franken_qwen27B_compressor_lora.pt")
|
| 267 |
+
elif qwen_id=="Qwen/Qwen3.5-2B":
|
| 268 |
+
return load_custom_checkpoint(qwen_model, filepath="./Downloads/franken_qwen2B_compressor_checkpoint.pt")
|
| 269 |
+
qwen_model.enable_input_require_grads()
|
| 270 |
+
return load_custom_checkpoint(qwen_model, filepath="/vault/franken_qwen27B_compressor_lora.pt")
|
| 271 |
+
|
| 272 |
+
# 全域模型初始化
|
| 273 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 274 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 275 |
+
MODEL_ID = "Qwen/Qwen3.5-2B"
|
| 276 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 277 |
+
model = build_franken_qwen(qwen_id=MODEL_ID, device="cuda")
|
| 278 |
+
model=model.get_base_model() if hasattr(model, "get_base_model") else model
|
| 279 |
+
model=torch.compile(model)
|
| 280 |
+
model.eval()
|
| 281 |
+
print(get_vram_status())
|
| 282 |
+
# ==========================================
|
| 283 |
+
# 3. OpenAI 官方相容的 Pydantic 資料模型定義
|
| 284 |
+
# ==========================================
|
| 285 |
+
class ChatMessage(BaseModel):
|
| 286 |
+
role: str
|
| 287 |
+
content: str
|
| 288 |
+
|
| 289 |
+
class ChatCompletionRequest(BaseModel):
|
| 290 |
+
# 🌟 關鍵優化:extra="allow" 允許 lm-eval 傳入額外的 OpenAI 參數 (如 n, logprobs) 而不報錯
|
| 291 |
+
model_config = ConfigDict(extra="allow")
|
| 292 |
+
model: str
|
| 293 |
+
messages: List[ChatMessage]
|
| 294 |
+
temperature: Optional[float] = 0.7
|
| 295 |
+
top_p: Optional[float] = 0.9
|
| 296 |
+
max_tokens: Optional[int] = Field(default=512, alias="max_tokens")
|
| 297 |
+
stream: Optional[bool] = False
|
| 298 |
+
stop: Optional[Union[str, List[str]]] = None # 🌟 接收 lm-eval 的停止符號
|
| 299 |
+
class CompletionRequest(BaseModel):
|
| 300 |
+
# 🌟 針對標準文字補全的 Request Schema
|
| 301 |
+
model_config = ConfigDict(extra="allow")
|
| 302 |
+
model: str
|
| 303 |
+
prompt: Union[str, List[str]]
|
| 304 |
+
temperature: Optional[float] = 0.7
|
| 305 |
+
top_p: Optional[float] = 0.9
|
| 306 |
+
max_tokens: Optional[int] = Field(default=512, alias="max_tokens")
|
| 307 |
+
stream: Optional[bool] = False
|
| 308 |
+
stop: Optional[Union[str, List[str]]] = None
|
| 309 |
+
# ==========================================
|
| 310 |
+
# 4. OpenAI 相容核心端點 (/v1/chat/completions)
|
| 311 |
+
# ==========================================
|
| 312 |
+
@app.exception_handler(Exception)
|
| 313 |
+
async def universal_exception_handler(request: Request, exc: Exception):
|
| 314 |
+
return JSONResponse(
|
| 315 |
+
status_code=500,
|
| 316 |
+
content={"error": {"message": f"Internal Server Error: {str(exc)}", "type": "server_error"}}
|
| 317 |
+
)
|
| 318 |
+
def prepare_gen_config(request, inputs):
|
| 319 |
+
"""公用生成參數建立函式"""
|
| 320 |
+
gen_config = {
|
| 321 |
+
**inputs,
|
| 322 |
+
"max_new_tokens": request.max_tokens,
|
| 323 |
+
"do_sample": True if request.temperature > 0 else False,
|
| 324 |
+
"temperature": request.temperature if request.temperature > 0 else None,
|
| 325 |
+
"top_p": request.top_p,
|
| 326 |
+
"repetition_penalty": 1.05,
|
| 327 |
+
"use_cache": True,
|
| 328 |
+
"pad_token_id": tokenizer.eos_token_id,
|
| 329 |
+
"eos_token_id": [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|im_end|>")]
|
| 330 |
+
}
|
| 331 |
+
# 🌟 處理 lm-eval 傳過來的 stop 截斷字串
|
| 332 |
+
if request.stop:
|
| 333 |
+
gen_config["stop_strings"] = [request.stop] if isinstance(request.stop, str) else request.stop
|
| 334 |
+
gen_config["tokenizer"] = tokenizer
|
| 335 |
+
return gen_config
|
| 336 |
+
@app.post("/v1/chat/completions")
|
| 337 |
+
async def chat_completions_endpoint(request: ChatCompletionRequest):
|
| 338 |
+
async with gpu_semaphore: # 佇列鎖管控
|
| 339 |
+
formatted_messages = [{"role": msg.role, "content": msg.content} for msg in request.messages]
|
| 340 |
+
input_text = tokenizer.apply_chat_template(formatted_messages, tokenize=False, add_generation_prompt=True)
|
| 341 |
+
inputs = tokenizer(input_text, return_tensors="pt", add_special_tokens=False).to(model.device)
|
| 342 |
+
gen_config = prepare_gen_config(request, inputs)
|
| 343 |
+
|
| 344 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 345 |
+
gen_config["streamer"] = streamer
|
| 346 |
+
threading.Thread(target=lambda: torch.no_grad()(model.generate)(**gen_config)).start()
|
| 347 |
+
|
| 348 |
+
if not request.stream:
|
| 349 |
+
# 🌟 優化:將同步阻塞的 "".join 丟進線程池,解放 Event Loop
|
| 350 |
+
full_text = await asyncio.to_thread(lambda: "".join([new_text for new_text in streamer]))
|
| 351 |
+
return {
|
| 352 |
+
"id": f"chatcmpl-{uuid.uuid4()}", "object": "chat.completion", "created": int(time.time()), "model": request.model,
|
| 353 |
+
"choices": [{"index": 0, "message": {"role": "assistant", "content": full_text}, "finish_reason": "stop"}],
|
| 354 |
+
"usage": {"prompt_tokens": inputs["input_ids"].shape[1], "completion_tokens": len(tokenizer.encode(full_text)), "total_tokens": inputs["input_ids"].shape[1] + len(tokenizer.encode(full_text))}
|
| 355 |
+
}
|
| 356 |
+
else:
|
| 357 |
+
async def openai_chat_stream():
|
| 358 |
+
chunk_id, created_time = f"chatcmpl-{uuid.uuid4()}", int(time.time())
|
| 359 |
+
yield f"data: {json.dumps({'id': chunk_id, 'object': 'chat.completion.chunk', 'created': created_time, 'model': request.model, 'choices': [{'index': 0, 'delta': {'role': 'assistant'}, 'finish_reason': None}]}, ensure_ascii=False)}\n\n"
|
| 360 |
+
|
| 361 |
+
# 🌟 優化:建立安全不阻塞事件循環的取 Token 函式
|
| 362 |
+
def get_next_token():
|
| 363 |
+
try:
|
| 364 |
+
return next(streamer), False
|
| 365 |
+
except StopIteration:
|
| 366 |
+
return "", True
|
| 367 |
+
|
| 368 |
+
while True:
|
| 369 |
+
# 🌟 關鍵:每次拿 Token 都讓出主執行緒,讓監控端點可以插隊進來執行
|
| 370 |
+
new_text, is_done = await asyncio.to_thread(get_next_token)
|
| 371 |
+
if is_done:
|
| 372 |
+
break
|
| 373 |
+
if new_text:
|
| 374 |
+
yield f"data: {json.dumps({'id': chunk_id, 'object': 'chat.completion.chunk', 'created': created_time, 'model': request.model, 'choices': [{'index': 0, 'delta': {'content': new_text}, 'finish_reason': None}]}, ensure_ascii=False)}\n\n"
|
| 375 |
+
|
| 376 |
+
yield f"data: {json.dumps({'id': chunk_id, 'object': 'chat.completion.chunk', 'created': created_time, 'model': request.model, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]}, ensure_ascii=False)}\n\n"
|
| 377 |
+
yield "data: [DONE]\n\n"
|
| 378 |
+
return StreamingResponse(openai_chat_stream(), media_type="text/event-stream")
|
| 379 |
+
|
| 380 |
+
# ----- 端點 B:文字接龍 (/v1/completions) -----
|
| 381 |
+
@app.post("/v1/completions")
|
| 382 |
+
async def completions_endpoint(request: CompletionRequest):
|
| 383 |
+
async with gpu_semaphore: # 佇列鎖管控
|
| 384 |
+
|
| 385 |
+
input_text = request.prompt[0] if isinstance(request.prompt, list) else request.prompt
|
| 386 |
+
inputs = tokenizer(input_text, return_tensors="pt", add_special_tokens=False).to(model.device)
|
| 387 |
+
gen_config = prepare_gen_config(request, inputs)
|
| 388 |
+
|
| 389 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 390 |
+
gen_config["streamer"] = streamer
|
| 391 |
+
threading.Thread(target=lambda: torch.no_grad()(model.generate)(**gen_config)).start()
|
| 392 |
+
|
| 393 |
+
if not request.stream:
|
| 394 |
+
full_text = "".join([new_text for new_text in streamer])
|
| 395 |
+
return {
|
| 396 |
+
"id": f"cmpl-{uuid.uuid4()}", "object": "text_completion", "created": int(time.time()), "model": request.model,
|
| 397 |
+
"choices": [{"text": full_text, "index": 0, "logprobs": None, "finish_reason": "stop"}],
|
| 398 |
+
"usage": {"prompt_tokens": inputs["input_ids"].shape[1], "completion_tokens": len(tokenizer.encode(full_text)), "total_tokens": inputs["input_ids"].shape[1] + len(tokenizer.encode(full_text))}
|
| 399 |
+
}
|
| 400 |
+
else:
|
| 401 |
+
async def openai_text_stream():
|
| 402 |
+
chunk_id, created_time = f"cmpl-{uuid.uuid4()}", int(time.time())
|
| 403 |
+
for new_text in streamer:
|
| 404 |
+
if new_text:
|
| 405 |
+
yield f"data: {json.dumps({'id': chunk_id, 'object': 'text_completion.chunk', 'created': created_time, 'model': request.model, 'choices': [{'text': new_text, 'index': 0, 'logprobs': None, 'finish_reason': None}]}, ensure_ascii=False)}\n\n"
|
| 406 |
+
yield f"data: {json.dumps({'id': chunk_id, 'object': 'text_completion.chunk', 'created': created_time, 'model': request.model, 'choices': [{'text': '', 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}]}, ensure_ascii=False)}\n\n"
|
| 407 |
+
yield "data: [DONE]\n\n"
|
| 408 |
+
return StreamingResponse(openai_text_stream(), media_type="text/event-stream")
|
| 409 |
+
|
| 410 |
+
# ==========================================
|
| 411 |
+
# 5. 補齊 OpenAI 的 /v1/models 查詢端點 (許多 UI 啟動時會先呼叫這個)
|
| 412 |
+
# ==========================================
|
| 413 |
+
@app.get("/v1/models")
|
| 414 |
+
async def list_models():
|
| 415 |
+
return {
|
| 416 |
+
"object": "list",
|
| 417 |
+
"data": [
|
| 418 |
+
{
|
| 419 |
+
"id": MODEL_ID,
|
| 420 |
+
"object": "model",
|
| 421 |
+
"created": int(time.time()),
|
| 422 |
+
"owned_by": "custom"
|
| 423 |
+
}
|
| 424 |
+
]
|
| 425 |
+
}
|
| 426 |
+
@app.get("/v1/debug/vram")
|
| 427 |
+
async def vram_monitor():
|
| 428 |
+
"""隨時動態查詢當前 GPU 記憶體狀態"""
|
| 429 |
+
return {
|
| 430 |
+
"object": "vram_status",
|
| 431 |
+
"data": get_vram_status()
|
| 432 |
+
}
|
| 433 |
+
if __name__ == "__main__":
|
| 434 |
+
uvicorn.run(app, host="127.0.0.1", port=8001)
|