lyi029 commited on
Commit
0cb9df5
·
1 Parent(s): 9f66df3
Files changed (1) hide show
  1. app.py +88 -4
app.py CHANGED
@@ -386,14 +386,72 @@ def _block_attention_score(tokens, chunk_size=512):
386
  scores.append(mean_attn.item())
387
  return float(np.mean(scores)) if scores else 0.0
388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  @app.post("/attention-heatmap")
390
  async def attention_heatmap(file: UploadFile = File(...)):
391
  """
392
  適用格式:整行以 '</s>' 分隔的 disasm tokens。
393
  每個 block 以 jump/call/ret 結束。
394
  最多取前 1000 個 block。
 
 
 
 
395
  """
396
- import io, sys, numpy as np, csv
397
  csv.field_size_limit(sys.maxsize)
398
 
399
  try:
@@ -429,16 +487,42 @@ async def attention_heatmap(file: UploadFile = File(...)):
429
  "score": score
430
  })
431
 
432
- avg_score = float(np.mean([b["score"] for b in results])) if results else 0.0
433
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  return {
435
  "num_blocks": len(results),
436
  "avg_attention": avg_score,
437
- "blocks": results
 
 
438
  }
439
 
440
  except Exception as e:
441
  print(f"❌ attention_heatmap error: {e}")
 
 
442
  return {"error": str(e)}
443
 
444
 
 
386
  scores.append(mean_attn.item())
387
  return float(np.mean(scores)) if scores else 0.0
388
 
389
+ # @app.post("/attention-heatmap")
390
+ # async def attention_heatmap(file: UploadFile = File(...)):
391
+ # """
392
+ # 適用格式:整行以 '</s>' 分隔的 disasm tokens。
393
+ # 每個 block 以 jump/call/ret 結束。
394
+ # 最多取前 1000 個 block。
395
+ # """
396
+ # import io, sys, numpy as np, csv
397
+ # csv.field_size_limit(sys.maxsize)
398
+
399
+ # try:
400
+ # # === 讀檔 ===
401
+ # content = await file.read()
402
+ # text = content.decode("utf-8", errors="ignore")
403
+
404
+ # # === 以 </s> 分隔整個 disasm ===
405
+ # lines = text.replace("\n", " ").split("</s>")
406
+ # tokens = []
407
+ # for line in lines:
408
+ # toks = [t.strip() for t in line.split() if t.strip()]
409
+ # if toks:
410
+ # tokens.extend(toks)
411
+
412
+ # print(f"📦 Total tokens parsed: {len(tokens)}")
413
+
414
+ # # === 拆 basic blocks ===
415
+ # blocks = _split_into_basic_blocks(tokens)
416
+ # print(f"📊 Total blocks before truncation: {len(blocks)}")
417
+
418
+ # # === 只取前 1000 個 block
419
+ # MAX_BLOCKS = int(os.getenv("MAX_HEATMAP_BLOCKS", "1000"))
420
+ # blocks = blocks[:MAX_BLOCKS]
421
+
422
+ # # === 計算每個 block 的 attention
423
+ # results = []
424
+ # for i, blk in enumerate(blocks):
425
+ # score = _block_attention_score(blk)
426
+ # results.append({
427
+ # "idx": i,
428
+ # "size": len(blk),
429
+ # "score": score
430
+ # })
431
+
432
+ # avg_score = float(np.mean([b["score"] for b in results])) if results else 0.0
433
+
434
+ # return {
435
+ # "num_blocks": len(results),
436
+ # "avg_attention": avg_score,
437
+ # "blocks": results
438
+ # }
439
+
440
+ # except Exception as e:
441
+ # print(f"❌ attention_heatmap error: {e}")
442
+ # return {"error": str(e)}
443
  @app.post("/attention-heatmap")
444
  async def attention_heatmap(file: UploadFile = File(...)):
445
  """
446
  適用格式:整行以 '</s>' 分隔的 disasm tokens。
447
  每個 block 以 jump/call/ret 結束。
448
  最多取前 1000 個 block。
449
+ 會同時回傳:
450
+ - blocks:每個 basic block 的注意力平均
451
+ - attention_heatmap:base64 圖像
452
+ - heatmap_matrix:數值陣列(可供前端繪圖)
453
  """
454
+ import io, sys, numpy as np, csv, base64, matplotlib.pyplot as plt
455
  csv.field_size_limit(sys.maxsize)
456
 
457
  try:
 
487
  "score": score
488
  })
489
 
490
+ if not results:
491
+ return {"error": "No valid blocks parsed"}
492
+
493
+ scores = [b["score"] for b in results]
494
+ avg_score = float(np.mean(scores))
495
+
496
+ # === 視覺化成 heatmap ===
497
+ fig, ax = plt.subplots(figsize=(10, 2))
498
+ heatmap_data = np.expand_dims(scores, axis=0)
499
+ im = ax.imshow(heatmap_data, cmap="viridis", aspect="auto")
500
+ plt.colorbar(im, ax=ax, orientation="vertical", label="Attention Score")
501
+ ax.set_title("Attention Heatmap per Basic Block")
502
+ ax.set_xlabel("Block Index")
503
+ ax.set_yticks([]) # 不需要 Y 軸
504
+ plt.tight_layout()
505
+
506
+ # === 轉成 base64 ===
507
+ buf = io.BytesIO()
508
+ plt.savefig(buf, format="png")
509
+ buf.seek(0)
510
+ img_base64 = base64.b64encode(buf.read()).decode("utf-8")
511
+ plt.close(fig)
512
+
513
+ # === 回傳 JSON ===
514
  return {
515
  "num_blocks": len(results),
516
  "avg_attention": avg_score,
517
+ "blocks": results,
518
+ "heatmap_matrix": heatmap_data.tolist(), # ✅ 可互動繪圖
519
+ "attention_heatmap": f"data:image/png;base64,{img_base64}" # ✅ 前端直接顯示
520
  }
521
 
522
  except Exception as e:
523
  print(f"❌ attention_heatmap error: {e}")
524
+ import traceback
525
+ traceback.print_exc()
526
  return {"error": str(e)}
527
 
528