Spaces:
Running
Running
Download coursework/chapter2_prompting/run.py from setariaa/nlp-sms-classifier: direct link, hf CLI and curl.
- Browser
- Download file 7.08 kB
-
https://huggingface.co/spaces/setariaa/nlp-sms-classifier/resolve/main/coursework/chapter2_prompting/run.py
- Command line
-
hf download hf://spaces/setariaa/nlp-sms-classifier/coursework/chapter2_prompting/run.py
-
curl -L -o run.py https://huggingface.co/spaces/setariaa/nlp-sms-classifier/resolve/main/coursework/chapter2_prompting/run.py
7.08 kB
| """Run controlled prompting experiments against a real local Qwen model.""" | |
| import ast, collections, json, operator, pathlib, re, sys | |
| sys.path.insert(0,str(pathlib.Path(__file__).resolve().parents[1])) | |
| from common.local_llm import LocalLLM, ROOT | |
| TASKS=[ | |
| ('lives','10 friends play a game. 7 quit. Each remaining player has 8 lives. How many lives remain in total?',24), | |
| ('cake','A cake takes 20 minutes for batter, 30 minutes to bake, 2 hours to cool, and 10 minutes to frost. It must be ready at 17:00. Return the latest start time as minutes after midnight.',840), | |
| ('eggs','Ducks lay 16 eggs daily. Janet eats 3 and uses 4 for muffins. She sells each remaining egg for 2 dollars. What is her daily revenue?',18), | |
| ('fiber','A robe takes 2 bolts of blue fiber and half that much white fiber. How many bolts in total?',3), | |
| ('house','A house costs 80000 dollars. Repairs cost 50000 dollars. Its value increases by 150 percent of its original price. What is the profit?',70000), | |
| ('feed','There are 20 chickens, each needs 3 cups of feed daily. They receive 15 cups in the morning and 25 cups at noon. How many cups remain to be fed?',20), | |
| ('books','A library has 48 books. A quarter are borrowed, then 7 books are returned. How many books are now available?',43), | |
| ('tickets','Three adult tickets cost 12 dollars each and two child tickets cost 7 dollars each. Pay with 60 dollars. What is the change?',10)] | |
| GOOD='Q: There are 15 trees and workers plant enough to reach 21. How many are planted?\nA: <answer>6</answer>\nQ: There are 3 cars and 2 more arrive. How many cars?\nA: <answer>5</answer>\n' | |
| COT='Q: There are 15 trees and workers plant enough to reach 21. How many are planted?\nA: 21 - 15 = 6. <answer>6</answer>\nQ: There are 3 cars and 2 more arrive. How many cars?\nA: 3 + 2 = 5. <answer>5</answer>\n' | |
| BAD=GOOD.replace('<answer>6','<answer>9').replace('<answer>5','<answer>8') | |
| def prompt(method,q): | |
| suffix='Return only the final number inside <answer>...</answer>.' | |
| if method=='pot':return 'Return ONLY JSON with one key "expression": a numeric Python arithmetic expression solving the question. No names, calls or functions. Example: {"expression":"(12-2)*3"}.\nQuestion: '+q | |
| prefix={'zero':'','few':GOOD,'cot':'','few_cot':COT,'wrong_few':BAD}[method] | |
| if method in ['cot','few_cot']:suffix='Give a brief calculation (at most 2 sentences), then the final number inside <answer>...</answer>.' | |
| return prefix+'Q: '+q+'\nA: '+suffix | |
| OPS={ast.Add:operator.add,ast.Sub:operator.sub,ast.Mult:operator.mul,ast.Div:operator.truediv,ast.USub:operator.neg,ast.UAdd:operator.pos} | |
| def safe_expression(s): | |
| if len(s)>150:raise ValueError('expression too long') | |
| def calc(n): | |
| if isinstance(n,ast.Constant) and type(n.value) in (int,float) and abs(n.value)<1e9:return n.value | |
| if isinstance(n,ast.BinOp) and type(n.op) in OPS:return OPS[type(n.op)](calc(n.left),calc(n.right)) | |
| if isinstance(n,ast.UnaryOp) and type(n.op) in OPS:return OPS[type(n.op)](calc(n.operand)) | |
| raise ValueError('unsupported expression') | |
| return calc(ast.parse(s,mode='eval').body) | |
| def parse_number(text,method): | |
| try: | |
| if method=='pot': | |
| obj=json.loads(text.strip().removeprefix('```json').removesuffix('```').strip()) | |
| return float(safe_expression(obj['expression'])) | |
| matches=re.findall(r'<answer>\s*([-+]?\d[\d,]*(?:\.\d+)?)\s*</answer>',text) | |
| return float(matches[-1].replace(',','')) if matches else None | |
| except (ValueError,TypeError,KeyError,SyntaxError,ZeroDivisionError,RecursionError):return None | |
| def main(): | |
| llm=LocalLLM();rows=[];log=ROOT/'results/prompting_raw.jsonl' | |
| with log.open('w',encoding='utf-8') as f: | |
| def record(row): | |
| rows.append(row);f.write(json.dumps(row,ensure_ascii=False)+'\n');f.flush() | |
| print(row['task'],row['method'],row.get('prediction'),flush=True) | |
| for method in ['zero','few','cot','few_cot','pot','wrong_few']: | |
| for tid,q,gold in TASKS: | |
| p=prompt(method,q);out=llm.generate(p,max_new_tokens=160) | |
| pred=parse_number(out['response'],method) | |
| record(dict(task=tid,question=q,gold=gold,method=method,prompt=p,prediction=pred,correct=pred is not None and abs(pred-gold)<1e-6,**out)) | |
| for tid,q,gold in TASKS: | |
| candidates=[] | |
| for k in range(5): | |
| p=prompt('cot',q);out=llm.generate(p,temperature=.7,seed=42+k,max_new_tokens=160) | |
| pred=parse_number(out['response'],'cot');candidates.append(pred) | |
| record(dict(task=tid,question=q,gold=gold,method='self_consistency_sample',sample=k,prompt=p,prediction=pred,correct=pred is not None and abs(pred-gold)<1e-6,**out)) | |
| counts=collections.Counter(x for x in candidates if x is not None);rank=counts.most_common() | |
| pred=rank[0][0] if rank and (len(rank)==1 or rank[0][1]>rank[1][1]) else None | |
| record(dict(task=tid,question=q,gold=gold,method='self_consistency',prediction=pred,correct=pred is not None and abs(pred-gold)<1e-6,samples=candidates,tie_policy='abstain')) | |
| # Same translation/aspect examples as the supplied chapter; demonstrations do not contain test answers. | |
| for mode in ['zero','few']: | |
| demos='sea otter => loutre de mer\npeppermint => menthe poivree\nplush giraffe => girafe peluche\n' if mode=='few' else '' | |
| p='Translate English to French. Return only the translation.\n'+demos+'cheese =>' | |
| record(dict(task='translation',method=mode,prompt=p,gold='fromage (optional article le)',**llm.generate(p,max_new_tokens=40))) | |
| demos='Review: It runs perfectly.\n[["runs","positive"]]\nReview: The service is awful.\n[["service","negative"]]\nReview: lots of extra space but the keyboard is ridiculously small.\n[["space","positive"],["keyboard","negative"]]\n' if mode=='few' else '' | |
| p='Extract aspect terms and their sentiment as JSON pairs. Return only JSON.\n'+demos+'Review: I can say that I am fully satisfied with the performance that the computer has supplied.' | |
| record(dict(task='aspect',method=mode,prompt=p,gold=[['performance','positive']],**llm.generate(p,max_new_tokens=80))) | |
| methods=['zero','few','cot','few_cot','pot','wrong_few','self_consistency'];summary={} | |
| for method in methods: | |
| sub=[r for r in rows if r['method']==method and r['task'] in {t[0] for t in TASKS}] | |
| summary[method]={'n':len(sub),'correct':sum(r['correct'] for r in sub),'accuracy':sum(r['correct'] for r in sub)/len(sub),'parse_failure_or_abstention':sum(r['prediction'] is None for r in sub)} | |
| result={'model':'Qwen/Qwen2.5-0.5B-Instruct','device':llm.device,'math_tasks':len(TASKS),'self_consistency_samples':5,'metrics':summary,'limits':'8 curated tasks; illustrative only. Translation/aspect outputs are qualitative and excluded from math accuracy.'} | |
| (ROOT/'results/prompting_metrics.json').write_text(json.dumps(result,indent=2,ensure_ascii=False),encoding='utf-8') | |
| if __name__=='__main__':main() | |