forked from Gen-Verse/LatentMAS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
81 lines (65 loc) · 2.16 KB
/
utils.py
File metadata and controls
81 lines (65 loc) · 2.16 KB
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
import os
import random
import re
from typing import Optional
import numpy as np
import torch
def set_seed(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
def auto_device(device: Optional[str] = None) -> torch.device:
if device is not None:
return torch.device(device)
if torch.cuda.is_available():
return torch.device("cuda")
return torch.device("cpu")
# this is to extract answer in \boxed{}
def extract_gsm8k_answer(text: str) -> Optional[str]:
boxes = re.findall(r"\\boxed\{([^}]*)\}", text)
if boxes:
content = boxes[-1]
number = re.search(r"[-+]?\d+(?:\.\d+)?", content)
return number.group(0) if number else content.strip()
numbers = re.findall(r"[-+]?\d+(?:\.\d+)?", text)
if numbers:
return numbers[-1]
return None
def extract_gold(text: str) -> Optional[str]:
match = re.search(r"####\s*([-+]?\d+(?:\.\d+)?)", text)
return match.group(1) if match else None
def normalize_answer(ans: Optional[str]) -> Optional[str]:
if ans is None:
return None
return ans.strip().lower()
def extract_markdown_python_block(text: str) -> Optional[str]:
pattern = r"```python(.*?)```"
matches = re.findall(pattern, text, re.DOTALL | re.IGNORECASE)
if matches:
return matches[-1].strip()
return None
# to run python
import traceback
from multiprocessing import Process, Manager
def run_with_timeout(code, timeout):
def worker(ns, code):
try:
local_ns = {}
exec(code, local_ns)
ns['ok'] = True
ns['error'] = None
except Exception:
ns['ok'] = False
ns['error'] = traceback.format_exc()
with Manager() as manager:
ns = manager.dict()
p = Process(target=worker, args=(ns, code))
p.start()
p.join(timeout)
if p.is_alive():
p.terminate()
ns['ok'] = False
ns['error'] = f"TimeoutError: Execution exceeded {timeout} seconds"
return ns.get('ok', False), ns.get('error', None)