Lab 3 — Parallelization: sectioning + voting (§19.1.3)
Lab walkthrough · EP04 Workflow Patterns
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP04 Workflow Patterns
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
เรียก LLM หลายครั้งพร้อมกัน แล้วให้โค้ดของเรารวมผล ตำราแบ่งเป็น 2 แบบ:
- Sectioning (fan-out) — แบ่งงานเป็นส่วนที่ไม่ทับกัน ทำแต่ละส่วนแยกกัน ตัวอย่างในตำรา: code review 🔒 security ∥ ⚡ performance ∥ 🎨 style → รวมผล · ตัดซ้ำ · เรียงตามความรุนแรง → เวลารวม ≈ call ที่ช้าที่สุด (max) ไม่ใช่ผลรวม (sum)
- Voting — prompt เดียวกัน N ครั้ง แล้วเลือกคำตอบด้วยเสียงข้างมาก (หรือ reward model / LLM-as-judge)
ธีม: ผู้ช่วยอาจารย์ของ Cogito Learn ช่วยตรวจโค้ดของระบบตัดเกรด
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.1.3 (p.370) — CC BY-SA 4.0
0. เตรียมเครื่อง
ต้องมี Python 3.10+ (หรือ Colab) และ OpenRouter API key — วิธีตั้งค่าอยู่ใน Lab 1
%pip install -q "openai>=1.50" python-dotenv# ---- จาก Lab 1: ตั้งค่า client + ask_llm ----
import os, json
from openai import OpenAI
def load_key():
try:
from google.colab import userdata
return userdata.get("OPENROUTER_API_KEY")
except ImportError:
from dotenv import load_dotenv
load_dotenv()
return os.environ["OPENROUTER_API_KEY"]
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key())
MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"provider": {"order": ["deepinfra/fp8"], "allow_fallbacks": False}, "reasoning": {"enabled": False}}
def ask_llm(prompt, temperature=0.7, schema=None):
kw = {"response_format": {"type": "json_schema", "json_schema": {"name": "out", "strict": True, "schema": schema}}} if schema else {}
resp = client.chat.completions.create(model=MODEL, extra_body=EXTRA, temperature=temperature,
messages=[{"role": "user", "content": prompt}], **kw)
text = resp.choices[0].message.content
return json.loads(text) if schema else textimport time
from concurrent.futures import ThreadPoolExecutor
from collections import Counter1. โค้ดที่จะตรวจ
ฟังก์ชันหาเด็กที่สอบตกของระบบตัดเกรด (ข้อมูลจำลองเพื่อการสอน — จงใจใส่ปัญหาไว้หลายด้าน)
CODE = '''import sqlite3
DB_PASSWORD = "cogito123"
def find_failing(db, student_names):
result = ""
for n in student_names:
q = "SELECT name, score FROM grades WHERE name = '" + n + "'"
row = db.execute(q).fetchone()
if row and row[1] < 50:
if row[0] not in result.split(","):
result = result + row[0] + ","
return result
'''
NUMBERED = "\n".join(f"{i:2} | {line}" for i, line in enumerate(CODE.splitlines(), 1))
print(NUMBERED) 1 | import sqlite3
2 |
3 | DB_PASSWORD = "cogito123"
4 |
5 | def find_failing(db, student_names):
6 | result = ""
7 | for n in student_names:
8 | q = "SELECT name, score FROM grades WHERE name = '" + n + "'"
9 | row = db.execute(q).fetchone()
10 | if row and row[1] < 50:
11 | if row[0] not in result.split(","):
12 | result = result + row[0] + ","
13 | return result
2. Sectioning: ผู้ตรวจ 3 ด้าน
แต่ละ reviewer ดู ด้านเดียว ไม่ทับกัน → ตอบเป็น JSON {line, severity, issue}
# ✏️ TODO 1 (▶ วิดีโอ 2:01): กำหนด reviewer 3 ด้าน (security / performance / style) แต่ละด้านบอกให้ดูเรื่องของตัวเองเท่านั้น
REVIEWERS = {
"security": "___",
"performance": "___",
"style": "___",
}REVIEWERS = {
"security": "security only: injection, secrets in code, unsafe input handling",
"performance": "performance only: slow loops, repeated work, wasted database calls",
"style": "style only: naming, readability, magic numbers, return types",
}FINDING = {"type": "object", "additionalProperties": False, "required": ["line", "severity", "issue"],
"properties": {"line": {"type": "integer"},
"severity": {"type": "string", "enum": ["high", "medium", "low"]},
"issue": {"type": "string"}}}
SCHEMA = {"type": "object", "additionalProperties": False, "required": ["findings"],
"properties": {"findings": {"type": "array", "minItems": 1, "items": FINDING}}}def review(aspect):
start = time.perf_counter()
# ✏️ TODO 2 (▶ วิดีโอ 2:51): เรียก LLM ด้วย prompt ของด้าน aspect + โค้ดที่มีเลขบรรทัด ใช้ temperature 0 และ SCHEMA
out = ask_llm(___, temperature=___, schema=___)
return aspect, out["findings"], time.perf_counter() - startdef review(aspect):
start = time.perf_counter()
out = ask_llm(f"You are a code reviewer. Review this Python code for {REVIEWERS[aspect]}. "
f"Ignore every other kind of problem. Give at most 3 findings, each with its line number "
f"and a one-sentence issue.\n\n{NUMBERED}", temperature=0, schema=SCHEMA)
return aspect, out["findings"], time.perf_counter() - startdef report(label, results, total):
for aspect, findings, sec in results:
print(f" {aspect:12} {sec:5.1f}s {len(findings)} findings")
times = [sec for _, _, sec in results]
print(f"⏱ {label}: {total:.1f}s | sum of calls = {sum(times):.1f}s | slowest call = {max(times):.1f}s")3. ทีละ call vs. พร้อมกัน
ทีละ call → เวลารวม ≈ sum · พร้อมกัน → เวลารวม ≈ max
start = time.perf_counter()
seq_results = [review(a) for a in REVIEWERS]
report("sequential", seq_results, time.perf_counter() - start) security 1.9s 2 findings
performance 2.5s 3 findings
style 2.5s 3 findings
⏱ sequential: 7.0s | sum of calls = 7.0s | slowest call = 2.5s
# ✏️ TODO 3 (▶ วิดีโอ 3:48): ส่ง review ทั้ง 3 ด้านพร้อมกันด้วย ThreadPoolExecutor แล้วเก็บผลเป็น list
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=___) as pool:
par_results = list(pool.___(review, REVIEWERS))
report("parallel", par_results, time.perf_counter() - start)start = time.perf_counter()
with ThreadPoolExecutor(max_workers=3) as pool:
par_results = list(pool.map(review, REVIEWERS))
report("parallel", par_results, time.perf_counter() - start) security 2.1s 2 findings
performance 2.1s 3 findings
style 2.0s 3 findings
⏱ parallel: 2.1s | sum of calls = 6.3s | slowest call = 2.1s
4. รวมผล · ตัดซ้ำ · เรียงตามความรุนแรง
ข้อที่อยู่ บรรทัดเดียวกัน = รายการเดียว (เก็บความรุนแรงที่สูงสุด + จดว่า reviewer ไหนเจอ)
SEVERITY = {"high": 0, "medium": 1, "low": 2}
def merge(results):
by_line = {}
for aspect, findings, _ in results:
for f in findings:
item = by_line.setdefault(f["line"], {"line": f["line"], "severity": "low", "by": [], "issues": []})
if aspect not in item["by"]:
item["by"].append(aspect)
item["issues"].append(f["issue"])
# ✏️ TODO 4 (▶ วิดีโอ 4:58): เก็บความรุนแรงที่สูงที่สุดของบรรทัด แล้วคืนรายการที่เรียงจาก high → low
if ___:
item["severity"] = f["severity"]
return sorted(by_line.values(), key=lambda x: (___, x["line"]))SEVERITY = {"high": 0, "medium": 1, "low": 2}
def merge(results):
by_line = {}
for aspect, findings, _ in results:
for f in findings:
item = by_line.setdefault(f["line"], {"line": f["line"], "severity": "low", "by": [], "issues": []})
if aspect not in item["by"]:
item["by"].append(aspect)
item["issues"].append(f["issue"])
if SEVERITY[f["severity"]] < SEVERITY[item["severity"]]:
item["severity"] = f["severity"]
return sorted(by_line.values(), key=lambda x: (SEVERITY[x["severity"]], x["line"]))merged = merge(par_results)
print(f"{sum(len(f) for _, f, _ in par_results)} findings → {len(merged)} items\n")
for m in merged:
print(f"[{m['severity']:6}] line {m['line']:2} ({' + '.join(m['by'])})")
for issue in m["issues"]:
print(" -", issue)8 findings → 6 items
[high ] line 3 (security)
- Hardcoded password 'cogito123' is stored in plain text within the source code.
[high ] line 8 (security + performance + style)
- The SQL query is constructed using string concatenation with the variable 'n', which is vulnerable to SQL injection.
- The code executes a separate database query inside a loop, causing an N+1 query problem.
- The variable name 'q' is too brief and should be renamed to 'query' to improve clarity.
[medium] line 10 (style)
- The magic number '50' should be extracted into a named constant to explain its significance.
[medium] line 11 (performance)
- The `result.split(',')` operation is performed repeatedly inside the loop, leading to redundant string processing.
[low ] line 7 (style)
- The variable name 'n' is non-descriptive and should be renamed to 'name' for better readability.
[low ] line 12 (performance)
- String concatenation in a loop creates new string objects repeatedly, which is inefficient for large datasets.
5. Voting: ถามคำถามเดียว 5 ครั้ง
prompt เดียวกัน · temperature สูง → คำตอบแต่ละครั้งต่างกันได้ → Counter นับ → เสียงข้างมาก
QUESTION = ("You review code for Cogito Learn, a university teaching-assistant app. "
"Rate the severity of this code-review finding as high, medium or low.\n\n"
"Finding: find_failing() never closes or commits the database connection it is given.")
VOTE = {"type": "object", "additionalProperties": False, "required": ["severity"],
"properties": {"severity": {"type": "string", "enum": ["high", "medium", "low"]}}}# ✏️ TODO 5 (▶ วิดีโอ 6:35): ถาม QUESTION หนึ่งครั้งด้วย temperature สูง (1.0) แล้วคืนค่า severity
def ask_once(_):
return ask_llm(QUESTION, temperature=___, schema=VOTE)[___]
with ThreadPoolExecutor(max_workers=5) as pool:
votes = list(pool.map(ask_once, range(5)))
print("votes:", votes)
# ✏️ TODO 6 (▶ วิดีโอ 6:57): นับเสียงด้วย Counter แล้วเอาคำตอบที่ได้เสียงมากที่สุด พร้อมจำนวนเสียง
winner, count = ___
print(f"🗳️ majority: {winner} ({count}/{len(votes)} agree)")def ask_once(_):
return ask_llm(QUESTION, temperature=1.0, schema=VOTE)["severity"]
with ThreadPoolExecutor(max_workers=5) as pool:
votes = list(pool.map(ask_once, range(5)))
print("votes:", votes)
winner, count = Counter(votes).most_common(1)[0]
print(f"🗳️ majority: {winner} ({count}/{len(votes)} agree)")votes: ['high', 'medium', 'high', 'high', 'high']
🗳️ majority: high (4/5 agree)
สรุป
| แบบ | ในโค้ด | ได้อะไร |
|---|---|---|
| Sectioning (fan-out) | REVIEWERS + review() + pool.map |
3 ด้านพร้อมกัน · เวลา ≈ max ไม่ใช่ sum |
| Merge | merge() |
ตัดซ้ำตามบรรทัด · เรียงตาม SEVERITY |
| Voting | ask_once() × 5 + Counter |
เสียงข้างมาก + จำนวนเสียงที่เห็นด้วย |
ลองทำต่อ: เพิ่ม reviewer ด้านที่ 4 เช่น "tests" ใน REVIEWERS แล้วจับเวลาอีกครั้ง — sequential ช้าลงแค่ไหน parallel ช้าลงแค่ไหน? และลองเปลี่ยนจำนวนเสียงโหวตจาก 5 เป็น 9 ดูว่าจำนวนเสียงที่เห็นด้วยนิ่งขึ้นไหม
ถัดไป: Lab 4 — Orchestrator-Workers