File size: 13,278 Bytes
49654fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""Shared parsing, JSONL and local-model helpers extracted from the original code."""
import json
import re
import os
import time
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parent
RESULTS_DIR = PROJECT_ROOT / "work" / "candidate_discovery"
STAGE1_OUT = str(PROJECT_ROOT / "work" / "query_curation" / "intent.jsonl")
MODEL_PATH = str(PROJECT_ROOT / "models" / "Qwen" / "Qwen3.6-27B")
MAX_IMAGE_PIXELS = 2 * 1024 * 1024

def extract_json_obj(text):
    """Extract a JSON object ({...}) from model output. Returns dict or fallback."""
    try:
        match = re.search(r"\{.*\}", text, re.DOTALL)
        if match:
            parsed = json.loads(match.group())
            if isinstance(parsed, dict):
                return parsed
    except (json.JSONDecodeError, ValueError):
        pass
    return {"content": "未知", "intent": "未知", "note": "未知", "_raw": text}

def extract_keywords(text):
    try:
        match = re.search(r"\[.*?\]", text, re.DOTALL)
        if match:
            parsed = json.loads(match.group())
            if isinstance(parsed, list) and all(isinstance(x, str) for x in parsed):
                return parsed
    except (json.JSONDecodeError, ValueError):
        pass

    lines = text.strip().split("\n")
    keywords = []
    for line in lines:
        line = line.strip()
        cleaned = re.sub(r"^[\d]+[.、)\]]\s*", "", line)
        cleaned = re.sub(r"^[-*·•]\s*", "", cleaned)
        cleaned = re.sub(r"\*\*(.+?)\*\*", r"\1", cleaned)
        cleaned = cleaned.split(":")[0].split(":")[0].strip()
        if cleaned and len(cleaned) < 30:
            keywords.append(cleaned)

    if not keywords:
        keywords = [k.strip() for k in text.split(",") if k.strip()]
    if not keywords:
        keywords = [k.strip() for k in text.split(",") if k.strip()]

    return keywords[:15]

def append_result(result, pipeline_name, out_dir=None):
    """增量追加 JSONL。"""
    base = Path(out_dir) if out_dir is not None else RESULTS_DIR
    base.mkdir(exist_ok=True, parents=True)
    out_path = base / f"{pipeline_name}.jsonl"
    with open(out_path, "a", encoding="utf-8") as f:
        f.write(json.dumps(result, ensure_ascii=False) + "\n")
        f.flush()

def load_done_idx(pipeline_name, out_dir=None):
    """读取已完成的 idx 集合,用于断点续存跳过。"""
    base = Path(out_dir) if out_dir is not None else RESULTS_DIR
    base.mkdir(exist_ok=True, parents=True)
    out_path = base / f"{pipeline_name}.jsonl"
    done = set()
    if out_path.exists():
        with open(out_path, encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if line:
                    try:
                        done.add(json.loads(line)["idx"])
                    except (json.JSONDecodeError, KeyError):
                        continue
    return done

def load_scenes(stage1_path=None):
    """读 Stage1 缓存 -> {idx: scene_dict}。这是下游模块消费 Stage1 输出的主接口。"""
    path = stage1_path or STAGE1_OUT
    scenes = {}
    if os.path.exists(path):
        with open(path, encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                try:
                    r = json.loads(line)
                    scenes[str(r["idx"])] = r
                except (json.JSONDecodeError, KeyError):
                    continue
    return scenes

def load_model_and_processor(model_path=None):
    import torch
    from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
    path = model_path or MODEL_PATH
    print(f"Loading processor from {path} ...")
    processor = AutoProcessor.from_pretrained(path, trust_remote_code=True)
    # 限制图片分辨率。
    processor.image_processor.size["longest_edge"] = MAX_IMAGE_PIXELS
    print(f"  max_pixels(longest_edge)={MAX_IMAGE_PIXELS}")

    print(f"Loading model (bf16, device_map=cuda) from {path} ...")
    t0 = time.time()
    model = Qwen3_5ForConditionalGeneration.from_pretrained(
        path,
        dtype=torch.bfloat16,
        device_map="cuda",
        trust_remote_code=True,
    )
    model.eval()
    print(f"Model loaded in {time.time() - t0:.1f}s")
    return model, processor

def strip_think_block(text):
    return re.sub(r"🤔.*?</think>\s*", "", text, flags=re.DOTALL).strip()

def run_text_only(model, processor, text_prompt, max_new_tokens=1024, enable_thinking=False,
                  do_sample=True, temperature=0.7, top_p=0.8, top_k=20, seed=None):
    import torch
    """纯文本推理(单条)。采样参数语义同 run_multimodal:默认采样兼容旧 pipeline,
    需可复现时传 do_sample=False + seed=0。"""
    tokenizer = processor.tokenizer
    messages = [{"role": "user", "content": text_prompt}]
    text = tokenizer.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True,
        enable_thinking=enable_thinking,
    )
    inputs = tokenizer(text, return_tensors="pt").to(model.device)
    if seed is not None:
        torch.manual_seed(seed)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(seed)
    gen_kwargs = dict(max_new_tokens=max_new_tokens, do_sample=do_sample)
    if do_sample:
        gen_kwargs.update(temperature=temperature, top_p=top_p, top_k=top_k)
    with torch.no_grad():
        output_ids = model.generate(**inputs, **gen_kwargs)
    generated = output_ids[0][inputs["input_ids"].shape[1]:]
    response = tokenizer.decode(generated, skip_special_tokens=True)
    if enable_thinking:
        return strip_think_block(response)
    return response.strip()

def run_text_only_batch(model, processor, prompts, batch_size=8, max_new_tokens=256,
                        enable_thinking=False, do_sample=True, temperature=0.7,
                        top_p=0.8, top_k=20, seed=None, sort_by_length=False,
                        show_progress=True):
    import torch
    """批量纯文本推理,保留输入顺序。"""
    tokenizer = processor.tokenizer
    n = len(prompts)
    if n == 0:
        return []

    # 1. 套 chat template(不 tokenize,留待批量 padding)
    chat_texts = []
    for p in prompts:
        messages = [{"role": "user", "content": p}]
        chat_texts.append(tokenizer.apply_chat_template(
            messages, tokenize=False, add_generation_prompt=True,
            enable_thinking=enable_thinking,
        ))

    # 2. 分桶顺序(按 prompt 长度升序,连续分批 → 同批长度接近、padding 最少)
    order = list(range(n))
    if sort_by_length:
        lens = [len(tokenizer(t, add_special_tokens=False)["input_ids"]) for t in chat_texts]
        order.sort(key=lambda i: lens[i])

    # 3. 设置 left-padding(decoder-only 生成必须)+ pad token
    prev_side = tokenizer.padding_side
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    tokenizer.padding_side = "left"

    results = [None] * n
    n_batches = (n + batch_size - 1) // batch_size
    try:
        gen_kwargs = dict(max_new_tokens=max_new_tokens, do_sample=do_sample)
        if do_sample:
            gen_kwargs.update(temperature=temperature, top_p=top_p, top_k=top_k)
        for bi, b_start in enumerate(range(0, n, batch_size)):
            batch_idx = order[b_start:b_start + batch_size]
            batch_texts = [chat_texts[i] for i in batch_idx]
            inputs = tokenizer(
                batch_texts, padding=True, return_tensors="pt",
            ).to(model.device)
            if seed is not None:
                torch.manual_seed(seed)
                if torch.cuda.is_available():
                    torch.cuda.manual_seed_all(seed)
            with torch.no_grad():
                output_ids = model.generate(**inputs, **gen_kwargs)
            # left-pad 下所有行 prompt 都被右对齐到同一长度,切掉前 input_len 即得新生成
            input_len = inputs["input_ids"].shape[1]
            gen_ids = output_ids[:, input_len:]
            for j, i in enumerate(batch_idx):
                text = tokenizer.decode(gen_ids[j], skip_special_tokens=True)
                if enable_thinking:
                    text = strip_think_block(text)
                results[i] = text.strip()
            if show_progress:
                done = b_start + len(batch_idx)
                print(f"  batch {bi + 1}/{n_batches} done ({done}/{n})", flush=True)
    finally:
        tokenizer.padding_side = prev_side

    return results



GRADE_ALIASES = {"L1": "L1", "L2": "L2", "N1": "N1", "N2": "N2", "N3": "N3",
                 "hard_neg_constraint": "N1", "hard_neg_lookalike": "N2", "irrelevant": "N3"}


def parse_grade(text):
    """Require an explicit valid JSON label; failed generation is not a vote."""
    obj = extract_json_obj(text)
    grade = obj.get("grade")
    if not isinstance(grade, str) or grade not in GRADE_ALIASES:
        raise ValueError("Model response does not contain a valid five-way grade")
    internal = {"N1": "hard_neg_constraint", "N2": "hard_neg_lookalike", "N3": "irrelevant"}
    return {"grade": internal.get(grade, grade), "reason": obj.get("reason")}


def read_jsonl(path):
    with open(path, encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def write_jsonl(path, rows):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as f:
        for row in rows:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")


def read_pairs(path):
    """Accept flat pairs or the historical per-query candidates format."""
    pairs = []
    for row in read_jsonl(path):
        if "item_id" in row:
            candidates = [row]
        elif isinstance(row.get("candidates"), list):
            candidates = row["candidates"]
        else:
            raise ValueError(f"Expected item_id or candidates in {path}")
        for candidate in candidates:
            pairs.append({**candidate, "idx": str(row["idx"]),
                          "item_id": str(candidate["item_id"])})
    return pairs


def pair_key(row):
    return str(row["idx"]), str(row["item_id"])


def index_pairs(rows):
    indexed = {}
    for row in rows:
        key = pair_key(row)
        if key in indexed:
            raise ValueError(f"Duplicate pair: {key}")
        indexed[key] = row
    return indexed


def leader_clusters(sub, gidxs, threshold):
    """按中心性降序分配;只吸收与 leader 直接相似的成员。sub 对角为 -1。"""
    m = len(gidxs)
    if m <= 1:
        return [list(gidxs)] if m else []
    cent = (sub.sum(axis=1) + 1.0) / (m - 1)
    order = sorted(range(m), key=lambda i: -float(cent[i]))
    assigned = [False] * m
    clusters = []
    for li in order:
        if assigned[li]:
            continue
        members = [li]
        assigned[li] = True
        for j in order:
            if assigned[j] or j == li:
                continue
            if float(sub[li][j]) >= threshold:
                members.append(j)
                assigned[j] = True
        clusters.append([gidxs[x] for x in members])
    return clusters


def select_representative(members, emb, kind):
    import numpy as np
    sub = emb[members]
    if kind == "query":
        centroid = sub.mean(axis=0)
        centroid /= np.linalg.norm(centroid) + 1e-9
        scores = sub @ centroid
    else:
        sim = sub @ sub.T
        np.fill_diagonal(sim, 0)
        scores = sim.sum(axis=1) / max(len(members) - 1, 1)
    return members[int(np.argmax(scores))]


def deduplicate(items, emb, kind, threshold=None):
    import numpy as np
    from collections import defaultdict
    threshold = threshold if threshold is not None else (0.70 if kind == "query" else 0.60)
    emb = np.asarray(emb, dtype=np.float32)
    if emb.ndim != 2 or len(emb) != len(items):
        raise ValueError("向量行数必须与输入记录一一对应")
    norms = np.linalg.norm(emb, axis=1, keepdims=True)
    if not np.isfinite(emb).all() or (norms == 0).any():
        raise ValueError("向量必须有限且非零")
    emb = emb / norms
    buckets = defaultdict(list)
    for i, row in enumerate(items):
        key = row["treecate_full_path"] if kind == "product" else "all"
        if not key:
            raise ValueError("商品必须有叶子类目的完整路径")
        buckets[key].append(i)
    kept, mapping = [], {}
    id_key = "idx" if kind == "query" else "item_id"
    for indices in buckets.values():
        sim = emb[indices] @ emb[indices].T
        np.fill_diagonal(sim, -1)
        for members in leader_clusters(sim, indices, threshold):
            rep = select_representative(members, emb, kind)
            kept.append(rep)
            for i in members:
                mapping[str(items[i][id_key])] = str(items[rep][id_key])
    return [items[i] for i in sorted(kept)], mapping


def load_embeddings(path, ids):
    import numpy as np
    with np.load(path, allow_pickle=False) as data:
        if list(map(str, data["ids"])) != list(map(str, ids)):
            raise ValueError("向量缓存的 ID 顺序与输入不一致")
        return data["emb"]