feat(prepare_inputs): 添加 part4_ids 构建逻辑并作为输入参数传递
This commit is contained in:
parent
079cbd21a1
commit
1e77c55ece
42
inference.py
42
inference.py
|
|
@ -265,6 +265,18 @@ class InputMethodInference:
|
|||
except:
|
||||
return f"[ID:{id}]"
|
||||
|
||||
def _build_part4_ids(
|
||||
self, words: List[str], max_words: int = 5, max_word_len: int = 6
|
||||
) -> torch.Tensor:
|
||||
part4_ids = torch.zeros(max_words, max_word_len, dtype=torch.long)
|
||||
if not words:
|
||||
return part4_ids
|
||||
for i, w in enumerate(words[:max_words]):
|
||||
tokens = self.tokenizer.encode(w, add_special_tokens=False)[:max_word_len]
|
||||
for j, t in enumerate(tokens):
|
||||
part4_ids[i, j] = t
|
||||
return part4_ids
|
||||
|
||||
def prepare_inputs(
|
||||
self,
|
||||
context_prompts: List[str],
|
||||
|
|
@ -289,26 +301,14 @@ class InputMethodInference:
|
|||
模型输入字典
|
||||
"""
|
||||
|
||||
# 1. 构建tokenizer输入
|
||||
# 根据test.py和dataset.py,格式为: "part4|part1" 和 part3
|
||||
# part4: 上下文提示(专有词汇、姓名等,模型不掌握)
|
||||
# part1: text_before
|
||||
# part3: text_after
|
||||
# 1. 构建 part4_ids (用户个人词库,单独的 input)
|
||||
part4_ids = self._build_part4_ids(context_prompts)
|
||||
|
||||
# 处理上下文提示
|
||||
context_text = "|".join(context_prompts) if context_prompts else ""
|
||||
|
||||
# 构建输入文本 - 与test.py保持一致
|
||||
# test.py: f"{part4}|{part1}" 作为第一个参数,part3作为第二个参数
|
||||
if context_text:
|
||||
input_text = f"{context_text}|{text_before}"
|
||||
else:
|
||||
input_text = text_before
|
||||
|
||||
# 2. Tokenize - 与test.py保持一致
|
||||
# 2. Tokenize 主文本 - 与 dataset.py 一致:part1 和 part3
|
||||
# part4 不作为文本拼接,而是作为独立的 part4_ids 传入模型
|
||||
encoded = self.tokenizer(
|
||||
input_text,
|
||||
text_after,
|
||||
text=text_before if text_before else "",
|
||||
text_pair=text_after if text_after else None,
|
||||
max_length=max_seq_len,
|
||||
padding="max_length",
|
||||
truncation=True,
|
||||
|
|
@ -316,8 +316,7 @@ class InputMethodInference:
|
|||
return_token_type_ids=True,
|
||||
)
|
||||
|
||||
# 3. 处理拼音输入 - 与test.py保持一致
|
||||
# 首先清理拼音字符串,处理退格键等特殊字符
|
||||
# 3. 处理拼音输入
|
||||
cleaned_pinyin = self._clean_pinyin_input(pinyin)
|
||||
|
||||
pinyin_ids = text_to_pinyin_ids(cleaned_pinyin)
|
||||
|
|
@ -330,11 +329,9 @@ class InputMethodInference:
|
|||
# 4. 处理历史槽位(用户已确认的输入历史)
|
||||
history_slot_ids = []
|
||||
for char in slot_chars:
|
||||
# 为每个槽位汉字查找ID(用户已确认的输入历史)
|
||||
char_id = self.char_to_id(char)
|
||||
history_slot_ids.append(char_id)
|
||||
|
||||
# 填充到8个槽位
|
||||
if len(history_slot_ids) < 8:
|
||||
history_slot_ids.extend([0] * (8 - len(history_slot_ids)))
|
||||
else:
|
||||
|
|
@ -349,6 +346,7 @@ class InputMethodInference:
|
|||
"attention_mask": encoded["attention_mask"].to(self.device),
|
||||
"pinyin_ids": pinyin_tensor.to(self.device),
|
||||
"history_slot_ids": history_tensor.to(self.device),
|
||||
"part4_ids": part4_ids.unsqueeze(0).to(self.device),
|
||||
}
|
||||
|
||||
return inputs
|
||||
|
|
|
|||
Loading…
Reference in New Issue