itsalissonsilva commited on
Commit
8eb2152
·
verified ·
1 Parent(s): e0897b0

Evaluate frozen base/adapter programs under audited nobody/seccomp runner with matched reference checks and exact quantum-state fidelity

Browse files
execution/execution.json ADDED
The diff for this file is too large to render. See raw diff
 
execution/quantum_sandbox.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fail-closed Linux worker for a restricted subset of quantum Python.
2
+
3
+ AST screening is combined with nobody UID, cleared environment, process/resource
4
+ limits and seccomp denial of filesystem opens, networking and process execution.
5
+ Libraries are imported/warmed in the parent before any untrusted code runs.
6
+ """
7
+
8
+ import ast
9
+ import contextlib
10
+ import ctypes
11
+ import ctypes.util
12
+ import errno
13
+ import importlib
14
+ import io
15
+ import multiprocessing as mp
16
+ import os
17
+ import resource
18
+
19
+ for variable in ["OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"]:
20
+ os.environ[variable] = "1"
21
+
22
+ import numpy as np
23
+
24
+ MODULES = {
25
+ "numpy",
26
+ "numpy.linalg",
27
+ "math",
28
+ "cmath",
29
+ "qiskit",
30
+ "qiskit.quantum_info",
31
+ "pennylane",
32
+ "cirq",
33
+ }
34
+ ATTRIBUTES = set(
35
+ "array asarray zeros ones eye pi sqrt exp sin cos conj conjugate transpose reshape flatten ravel squeeze astype complex64 complex128 float32 float64 norm kron real imag T shape size data QuantumCircuit Statevector from_instruction h x y z ry rx rz cx cz swap s sdg t tdg sx barrier append device qnode state RY RX RZ Rot PhaseShift Identity PauliX PauliY PauliZ Hadamard CNOT CZ SWAP LineQubit range Circuit Simulator simulate final_state_vector H X Y Z CXPowGate ZPowGate XPowGate HPowGate controlled on inverse quantum_info".split()
36
+ )
37
+ BUILTINS = {
38
+ "range": lambda *a: bounded_range(*a),
39
+ "enumerate": enumerate,
40
+ "zip": zip,
41
+ "len": len,
42
+ "list": list,
43
+ "tuple": tuple,
44
+ "float": float,
45
+ "int": int,
46
+ "complex": complex,
47
+ "print": print,
48
+ "abs": abs,
49
+ "sum": sum,
50
+ "min": min,
51
+ "max": max,
52
+ "reversed": reversed,
53
+ }
54
+ FORBIDDEN = (
55
+ ast.ClassDef,
56
+ ast.AsyncFunctionDef,
57
+ ast.Await,
58
+ ast.While,
59
+ ast.Try,
60
+ ast.With,
61
+ ast.AsyncWith,
62
+ ast.Raise,
63
+ ast.Delete,
64
+ ast.Global,
65
+ ast.Nonlocal,
66
+ ast.Lambda,
67
+ ast.Yield,
68
+ ast.YieldFrom,
69
+ ast.Match,
70
+ )
71
+ LIB = None
72
+
73
+
74
+ def bounded_range(*args):
75
+ value = range(*args)
76
+ if len(value) > 1024:
77
+ raise ValueError("range limit")
78
+ return value
79
+
80
+
81
+ def screen(program):
82
+ if len(program) > 25000:
83
+ raise ValueError("program length limit")
84
+ tree = ast.parse(program)
85
+ if sum(1 for _ in ast.walk(tree)) > 6000:
86
+ raise ValueError("AST node limit")
87
+ for node in ast.walk(tree):
88
+ if isinstance(node, FORBIDDEN):
89
+ raise ValueError("unsupported syntax: " + type(node).__name__)
90
+ if isinstance(node, ast.Name) and (
91
+ node.id.startswith("_")
92
+ or node.id
93
+ in {
94
+ "eval",
95
+ "exec",
96
+ "compile",
97
+ "open",
98
+ "getattr",
99
+ "setattr",
100
+ "globals",
101
+ "locals",
102
+ "vars",
103
+ "type",
104
+ "object",
105
+ "input",
106
+ "help",
107
+ "breakpoint",
108
+ }
109
+ ):
110
+ raise ValueError("forbidden name")
111
+ if isinstance(node, ast.Attribute) and node.attr not in ATTRIBUTES:
112
+ raise ValueError("unsupported attribute: " + node.attr)
113
+ if isinstance(node, ast.Import):
114
+ if any(a.name not in MODULES or (a.asname or "").startswith("_") for a in node.names):
115
+ raise ValueError("unsupported import")
116
+ if isinstance(node, ast.ImportFrom):
117
+ if (
118
+ node.level
119
+ or node.module not in MODULES
120
+ or any(
121
+ a.name not in ATTRIBUTES or (a.asname or "").startswith("_") for a in node.names
122
+ )
123
+ ):
124
+ raise ValueError("unsupported from import")
125
+ if isinstance(node, ast.FunctionDef) and node.name.startswith("_"):
126
+ raise ValueError("forbidden function name")
127
+ return tree
128
+
129
+
130
+ def initialize():
131
+ global LIB
132
+ assert os.name == "posix" and os.getuid() == 0, "Linux root parent required for UID isolation"
133
+ # Resolve/load seccomp before restricting filesystem access.
134
+ library = ctypes.util.find_library("seccomp")
135
+ assert library, "libseccomp is required; never fall back to AST-only execution"
136
+ LIB = ctypes.CDLL(library, use_errno=True)
137
+ LIB.seccomp_init.argtypes = [ctypes.c_uint32]
138
+ LIB.seccomp_init.restype = ctypes.c_void_p
139
+ LIB.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
140
+ LIB.seccomp_syscall_resolve_name.restype = ctypes.c_int
141
+ LIB.seccomp_rule_add.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_uint]
142
+ LIB.seccomp_load.argtypes = [ctypes.c_void_p]
143
+ LIB.seccomp_release.argtypes = [ctypes.c_void_p]
144
+ from qiskit import QuantumCircuit
145
+ from qiskit.quantum_info import Statevector
146
+ import pennylane as qml
147
+ import cirq
148
+
149
+ qc = QuantumCircuit(2)
150
+ qc.h(0)
151
+ qc.ry(0.3, 1)
152
+ qc.x(0)
153
+ qc.z(1)
154
+ qc.cx(0, 1)
155
+ Statevector.from_instruction(qc)
156
+ device = qml.device("default.qubit", wires=[1, 0])
157
+
158
+ @qml.qnode(device)
159
+ def warm():
160
+ qml.Hadamard(0)
161
+ qml.RY(0.3, wires=1)
162
+ qml.PauliX(0)
163
+ qml.PauliZ(1)
164
+ qml.CNOT(wires=[0, 1])
165
+ return qml.state()
166
+
167
+ warm()
168
+ qubits = cirq.LineQubit.range(2)
169
+ cirq.Simulator(dtype=np.complex128).simulate(
170
+ cirq.Circuit(
171
+ cirq.H(qubits[0]),
172
+ cirq.ry(0.3)(qubits[1]),
173
+ cirq.X(qubits[0]),
174
+ cirq.Z(qubits[1]),
175
+ cirq.CNOT(*qubits),
176
+ ),
177
+ qubit_order=list(reversed(qubits)),
178
+ )
179
+ # Warm Python import machinery and serialization before fork/lockdown.
180
+ for module in MODULES:
181
+ importlib.import_module(module)
182
+ importlib.import_module("socket")
183
+ return dict(
184
+ qiskit=importlib.import_module("qiskit").__version__,
185
+ pennylane=qml.__version__,
186
+ cirq=cirq.__version__,
187
+ )
188
+
189
+
190
+ def lockdown():
191
+ os.environ.clear()
192
+ os.setgroups([])
193
+ os.setgid(65534)
194
+ os.setuid(65534)
195
+ resource.setrlimit(resource.RLIMIT_CPU, (15, 15))
196
+ # Native numeric runtimes reserve large virtual address spaces. Physical
197
+ # memory remains bounded by the HF CPU job container's memory allocation.
198
+ resource.setrlimit(resource.RLIMIT_AS, (16 * 1024**3, 16 * 1024**3))
199
+ resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0))
200
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
201
+ resource.setrlimit(resource.RLIMIT_NPROC, (32, 32))
202
+ libc = ctypes.CDLL(None, use_errno=True)
203
+ assert libc.prctl(38, 1, 0, 0, 0) == 0, "PR_SET_NO_NEW_PRIVS failed"
204
+ policy = LIB.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW
205
+ assert policy
206
+ deny = 0x00050000 | errno.EPERM # SCMP_ACT_ERRNO(EPERM)
207
+ for name in [
208
+ "open",
209
+ "openat",
210
+ "openat2",
211
+ "creat",
212
+ "socket",
213
+ "socketpair",
214
+ "connect",
215
+ "accept",
216
+ "accept4",
217
+ "bind",
218
+ "listen",
219
+ "sendto",
220
+ "sendmsg",
221
+ "execve",
222
+ "execveat",
223
+ "ptrace",
224
+ "process_vm_readv",
225
+ "process_vm_writev",
226
+ "mount",
227
+ "umount2",
228
+ "bpf",
229
+ "userfaultfd",
230
+ ]:
231
+ syscall = LIB.seccomp_syscall_resolve_name(name.encode())
232
+ if syscall >= 0:
233
+ assert LIB.seccomp_rule_add(policy, deny, syscall, 0) == 0, name
234
+ assert LIB.seccomp_load(policy) == 0, "seccomp load failed"
235
+ LIB.seccomp_release(policy)
236
+
237
+
238
+ def safe_import(name, globals=None, locals=None, fromlist=(), level=0):
239
+ if name not in MODULES or level:
240
+ raise ImportError("module not allowed")
241
+ module = importlib.import_module(name)
242
+ return module if fromlist else importlib.import_module(name.split(".")[0])
243
+
244
+
245
+ def worker(program, qubits, connection, mode):
246
+ try:
247
+ lockdown()
248
+ if mode == "isolation_check":
249
+ import socket
250
+
251
+ file_blocked = network_blocked = False
252
+ try:
253
+ open("/etc/hostname").read()
254
+ except PermissionError:
255
+ file_blocked = True
256
+ try:
257
+ socket.socket()
258
+ except PermissionError:
259
+ network_blocked = True
260
+ connection.send(
261
+ dict(
262
+ file_opens_blocked=file_blocked,
263
+ network_blocked=network_blocked,
264
+ uid=os.getuid(),
265
+ environment_empty=not os.environ,
266
+ )
267
+ )
268
+ return
269
+ tree = screen(program)
270
+ safe = dict(BUILTINS, __import__=safe_import)
271
+ namespace = {"__builtins__": safe}
272
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
273
+ exec(compile(tree, "<restricted-quantum>", "exec"), namespace, namespace)
274
+ value = np.asarray(namespace["state"], dtype=np.complex128).reshape(-1)
275
+ assert value.shape == (2**qubits,) and np.isfinite(value).all()
276
+ connection.send(
277
+ dict(
278
+ status="executed",
279
+ real=value.real.tolist(),
280
+ imag=value.imag.tolist(),
281
+ norm=float(np.linalg.norm(value)),
282
+ )
283
+ )
284
+ except BaseException as error:
285
+ connection.send(
286
+ dict(status="rejected_or_error", error=type(error).__name__, detail=str(error)[:300])
287
+ )
288
+ finally:
289
+ connection.close()
290
+
291
+
292
+ def run(program, qubits, mode="program"):
293
+ assert 1 <= qubits <= 8
294
+ ctx = mp.get_context("fork")
295
+ receive, send = ctx.Pipe(duplex=False)
296
+ process = ctx.Process(target=worker, args=(program, qubits, send, mode))
297
+ process.start()
298
+ send.close()
299
+ if receive.poll(20):
300
+ try:
301
+ result = receive.recv()
302
+ except EOFError:
303
+ result = dict(status="worker_exit", exitcode=process.exitcode)
304
+ else:
305
+ result = dict(status="timeout")
306
+ process.join(1)
307
+ if process.is_alive():
308
+ process.kill()
309
+ process.join(2)
310
+ receive.close()
311
+ return result
execution/train_quantum_execute_pilot.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent frozen-executor evaluation of base/adapted quantum programs."""
2
+
3
+ import ast
4
+ import hashlib
5
+ import json
6
+ import re
7
+ from collections import defaultdict
8
+ from pathlib import Path
9
+ import numpy as np
10
+ import pyarrow.parquet as pq
11
+ from huggingface_hub import HfApi, hf_hub_download
12
+ import quantum_sandbox as sandbox
13
+
14
+ REPO = "itsalissonsilva/QuantumCoder-9B"
15
+
16
+
17
+ def main():
18
+ api = HfApi()
19
+ revision = api.model_info(REPO).sha
20
+
21
+ def get(path):
22
+ return Path(hf_hub_download(REPO, path, revision=revision))
23
+
24
+ preflight = json.loads(get("executor_preflight/preflight.json").read_text())
25
+ assert preflight["all_passed"] and len(preflight["reference_checks"]) == 90
26
+ source_hash = hashlib.sha256(Path(sandbox.__file__).read_bytes()).hexdigest()
27
+ assert (
28
+ source_hash
29
+ == hashlib.sha256(get("executor_preflight/quantum_sandbox.py").read_bytes()).hexdigest()
30
+ ), "Do not change the executor after opening model programs"
31
+ generations = json.loads(get("hf_pilot/generation_report.json").read_text())
32
+ data = {}
33
+ for split in ["validation", "test"]:
34
+ rows = pq.read_table(
35
+ hf_hub_download(
36
+ generations["data_repo"],
37
+ f"data/{split}.parquet",
38
+ repo_type="dataset",
39
+ revision=generations["data_revision"],
40
+ )
41
+ ).to_pylist()
42
+ data.update({r["id"]: r for r in rows})
43
+ ids = [r["id"] for r in generations["conditions"]["base"]]
44
+ assert len(ids) == 192 and len(set(ids)) == 192
45
+ assert ids == [r["id"] for r in generations["conditions"]["adapted"]]
46
+ versions = sandbox.initialize()
47
+ isolation = sandbox.run("", 1, mode="isolation_check")
48
+ assert isolation == preflight["isolation"]
49
+
50
+ def execute(program, row):
51
+ # Unwrap only a single full-output code fence. No prose, repairs or
52
+ # target-informed program edits are allowed.
53
+ wrapped = re.fullmatch(r"\s*```(?:python)?\s*\n(.*?)\n```\s*", program, flags=re.S)
54
+ clean = wrapped.group(1) if wrapped else program
55
+ syntax = True
56
+ imports = set()
57
+ try:
58
+ tree = ast.parse(clean)
59
+ for node in ast.walk(tree):
60
+ if isinstance(node, ast.Import):
61
+ imports.update(a.name.split(".")[0] for a in node.names)
62
+ elif isinstance(node, ast.ImportFrom):
63
+ imports.add((node.module or "").split(".")[0])
64
+ except SyntaxError:
65
+ syntax = False
66
+ result = sandbox.run(clean, row["qubits"])
67
+ fidelity = None
68
+ state_pass = False
69
+ if result.get("status") == "executed":
70
+ actual = np.array(result["real"]) + 1j * np.array(result["imag"])
71
+ target = np.array(row["state_real"]) + 1j * np.array(row["state_imag"])
72
+ fidelity = float(abs(np.vdot(target, actual)) ** 2)
73
+ state_pass = abs(result["norm"] - 1) < 1e-6 and fidelity > 1 - 1e-6
74
+ requested = row["framework"] in imports
75
+ execution = {k: v for k, v in result.items() if k not in ["real", "imag"]}
76
+ return dict(
77
+ syntax_parses=syntax,
78
+ requested_framework_import=requested,
79
+ single_fence_unwrapped=wrapped is not None,
80
+ execution=execution,
81
+ state_pass=state_pass,
82
+ fidelity=fidelity,
83
+ passed=state_pass and requested,
84
+ program_sha256=hashlib.sha256(program.encode()).hexdigest(),
85
+ )
86
+
87
+ # Every selected reference must pass the same evaluator before scoring models.
88
+ reference_checks = []
89
+ for identifier in ids:
90
+ row = data[identifier]
91
+ outcome = execute(row["program"], row)
92
+ assert outcome["passed"], (identifier, outcome)
93
+ reference_checks.append(dict(id=identifier, **outcome))
94
+ records = []
95
+ for condition, outputs in generations["conditions"].items():
96
+ for output in outputs:
97
+ row = data[output["id"]]
98
+ assert row["framework"] == output["framework"] and row["qubits"] == output["qubits"]
99
+ assert np.allclose(row["state_real"], output["target_real"], atol=1e-12, rtol=0)
100
+ assert np.allclose(row["state_imag"], output["target_imag"], atol=1e-12, rtol=0)
101
+ records.append(
102
+ dict(
103
+ condition=condition,
104
+ id=row["id"],
105
+ group_id=row["group_id"],
106
+ split=output["split"],
107
+ framework=row["framework"],
108
+ generated_tokens=output["generated_tokens"],
109
+ possible_token_cap=output["generated_tokens"] >= 512,
110
+ **execute(output["program"], row),
111
+ )
112
+ )
113
+ print(
114
+ json.dumps(
115
+ dict(
116
+ stage="scored",
117
+ condition=condition,
118
+ passed=sum(r["passed"] for r in records if r["condition"] == condition),
119
+ )
120
+ ),
121
+ flush=True,
122
+ )
123
+ summary = {}
124
+ for condition in ["base", "adapted"]:
125
+ summary[condition] = {}
126
+ for split in ["validation", "test"]:
127
+ chosen = [r for r in records if r["condition"] == condition and r["split"] == split]
128
+ summary[condition][split] = dict(
129
+ n=len(chosen),
130
+ passed=sum(r["passed"] for r in chosen),
131
+ pass_at_1=float(np.mean([r["passed"] for r in chosen])),
132
+ state_correct=sum(r["state_pass"] for r in chosen),
133
+ executed=sum(r["execution"].get("status") == "executed" for r in chosen),
134
+ syntax_valid=sum(r["syntax_parses"] for r in chosen),
135
+ requested_import=sum(r["requested_framework_import"] for r in chosen),
136
+ possible_token_cap=sum(r["possible_token_cap"] for r in chosen),
137
+ )
138
+ base = {r["id"]: r for r in records if r["condition"] == "base" and r["split"] == "test"}
139
+ adapted = {r["id"]: r for r in records if r["condition"] == "adapted" and r["split"] == "test"}
140
+ keys = sorted(base)
141
+ delta = np.array([int(adapted[k]["passed"]) - int(base[k]["passed"]) for k in keys])
142
+ groups = defaultdict(list)
143
+ for i, k in enumerate(keys):
144
+ groups[base[k]["group_id"]].append(i)
145
+ indices = list(groups.values())
146
+ rng = np.random.default_rng(20261031)
147
+ boot = [
148
+ float(delta[np.concatenate([indices[i] for i in draw])].mean())
149
+ for draw in rng.integers(0, len(indices), size=(2000, len(indices)))
150
+ ]
151
+ report = dict(
152
+ source_revision=revision,
153
+ executor_sha256=source_hash,
154
+ versions=versions,
155
+ isolation=isolation,
156
+ data_revision=generations["data_revision"],
157
+ reference_checks=reference_checks,
158
+ records=records,
159
+ summary=summary,
160
+ paired_test=dict(
161
+ improved=int(np.sum(delta == 1)),
162
+ regressed=int(np.sum(delta == -1)),
163
+ mean_pass_delta=float(delta.mean()),
164
+ group_bootstrap_95=np.quantile(boot, [0.025, 0.975]).tolist(),
165
+ groups=len(indices),
166
+ ),
167
+ limitations="One synthetic held-out-framework experiment. Pass requires requested-framework import, supported-Python execution, unit norm and global-phase-invariant exact-state fidelity >1-1e-6. Import presence is a proxy for framework compliance, not a formal data-flow proof. Unsupported valid Python is rejected and can yield conservative false negatives. Only a full-output code fence may be removed. No repairs, retries or generated-code access to files/network. Original batch-width at_token_cap flag is unreliable and not used; generated_tokens>=512 is reported as a possible cap, not an exact stop reason.",
168
+ )
169
+ report["release_gate_pass"] = (
170
+ summary["adapted"]["test"]["passed"] > summary["base"]["test"]["passed"]
171
+ )
172
+ folder = Path("quantum_execution")
173
+ folder.mkdir(exist_ok=True)
174
+ (folder / "execution.json").write_text(json.dumps(report, indent=2))
175
+ (folder / "train_quantum_execute_pilot.py").write_bytes(Path(__file__).read_bytes())
176
+ (folder / "quantum_sandbox.py").write_bytes(Path(sandbox.__file__).read_bytes())
177
+ api.upload_folder(
178
+ repo_id=REPO,
179
+ folder_path=str(folder),
180
+ path_in_repo="execution",
181
+ commit_message="Evaluate frozen base/adapter programs under audited nobody/seccomp runner with matched reference checks and exact quantum-state fidelity",
182
+ )
183
+ print(
184
+ json.dumps(
185
+ dict(summary=summary, gate=report["release_gate_pass"], paired=report["paired_test"])
186
+ ),
187
+ flush=True,
188
+ )
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()