Spaces:
Sleeping
Sleeping
File size: 5,180 Bytes
3d01a8f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | """
代码片段 → 方法名建议工具
基于 fine-tune 的 CodeT5-small + ONNX 加速
支持 CPU,输出多个候选方法名
调试开关默认关闭
单例模式,避免重复加载模型
"""
import threading
import time
from typing import List, Optional
import torch
from transformers import AutoTokenizer, T5ForConditionalGeneration
from optimum.onnxruntime import ORTModelForSeq2SeqLM
class CodeNameSuggester:
_instance = None
_lock = threading.Lock()
_initialized = False
def __new__(cls, *args, **kwargs):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(
self,
model_name_or_path: str = "KyrieChao/code-method-namer",
device: str = "cpu",
max_input_len: int = 256,
max_output_len: int = 32,
num_beams: int = 4,
num_candidates: int = 3,
debug: bool = False,
force_reload: bool = False,
):
if self._initialized and not force_reload:
return
with self._lock:
if self._initialized and not force_reload:
return
print("🚀 首次加载模型...")
self.device = device
self.max_input_len = max_input_len
self.max_output_len = max_output_len
self.num_beams = num_beams
self.num_candidates = num_candidates
self.debug = debug
self.ort_model = None
self.pytorch_model = None
self.tokenizer = None
self._load_model(model_name_or_path)
if self.tokenizer.pad_token_id is None:
self.tokenizer.pad_token_id = self.tokenizer.eos_token_id or 0
if self.tokenizer.eos_token_id is None:
self.tokenizer.eos_token_id = 1
self._initialized = True
print("✅ 模型热加载完成")
def _load_model(self, model_name_or_path: str):
# 尝试 ONNX
try:
print(" 尝试 ONNX...")
self.ort_model = ORTModelForSeq2SeqLM.from_pretrained(
model_name_or_path,
provider="CPUExecutionProvider" if self.device == "cpu" else "CUDAExecutionProvider",
)
self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
print(" ✅ ONNX 加载成功")
return
except Exception as e:
print(f" ONNX 失败: {e}")
# 回退 PyTorch
print(" 加载 PyTorch...")
self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
self.pytorch_model = T5ForConditionalGeneration.from_pretrained(model_name_or_path)
self.pytorch_model.to(self.device)
self.pytorch_model.eval()
print(" ✅ PyTorch 加载成功")
@staticmethod
def clean_name(name: str) -> str:
name = name.strip().replace(" ", "_").replace("-", "_").strip("_")
return name[:60] if len(name) >= 2 else "unknown_name"
def suggest(self, code_snippet: str, num_candidates: Optional[int] = None) -> List[str]:
use_num = min(num_candidates or self.num_candidates, self.num_beams)
prompt = code_snippet.strip()
start_time = time.time()
inputs = self.tokenizer(
prompt,
max_length=self.max_input_len,
truncation=True,
return_tensors="pt",
padding=True
)
gen_kwargs = {
"max_length": self.max_output_len,
"num_beams": self.num_beams,
"early_stopping": True,
"no_repeat_ngram_size": 2,
"pad_token_id": self.tokenizer.pad_token_id,
"eos_token_id": self.tokenizer.eos_token_id,
}
# 关键:ONNX 只支持单序列生成
if self.ort_model:
outputs = self.ort_model.generate(**inputs, **gen_kwargs)
all_outputs = [outputs[0]] # 单条
else:
gen_kwargs["num_return_sequences"] = use_num
with torch.no_grad():
outputs = self.pytorch_model.generate(
inputs.input_ids.to(self.device),
attention_mask=inputs.attention_mask.to(self.device),
**gen_kwargs
)
all_outputs = outputs
elapsed = time.time() - start_time
suggestions = []
seen = set()
for out in all_outputs:
decoded = self.tokenizer.decode(out, skip_special_tokens=True).strip()
cleaned = self.clean_name(decoded)
if cleaned and cleaned not in seen and cleaned != "unknown_name":
seen.add(cleaned)
suggestions.append(cleaned)
if len(suggestions) >= use_num:
break
print(f"⏱️ {elapsed:.3f}s | 建议: {suggestions}")
return suggestions
def get_suggester(model_name_or_path: str = "KyrieChao/code-method-namer", device: str = "cpu"):
return CodeNameSuggester(model_name_or_path=model_name_or_path, device=device) |