Spaces:
Runtime error
Runtime error
Added some additional parameters to control `RestrictedPython` behavior.
Browse filesFiles changed (2)
- README.md+10-2
- restrictedpython_code_eval.py+207-7
45 unmodified lines464748495051521 unmodified line5455565758596045 unmodified lines**`timeout`** (`float`): The maximum time taken to produce a prediction before it is considered a "timeout". The default value is `3.0` (i.e. 3 seconds).In addition, this metric supports three additional arguments, specifying which default imports should be made available:**`use_safe_builtins`** (`bool`): Whether or not to allow the usage of [`RestrictedPython.safe_builtins`](https://github.com/zopefoundation/RestrictedPython/blob/c31c133844ac2308f5cc930e934a7227a2a6a77b/src/RestrictedPython/Guards.py#L23), defaults to True1 unmodified line**`use_utility_builtins`** (`bool`): Whether or not to allow the usage of [`RestrictedPython.utility_builtins`](https://github.com/zopefoundation/RestrictedPython/blob/c31c133844ac2308f5cc930e934a7227a2a6a77b/src/RestrictedPython/Utilities.py#L19), which includes the `string`, `math`, `random`, and `set` packages, among others. Defaults to True.As the additional arguments are optional, this could be used as a drop-in replacement for `code_eval`.### Output Values45 unmodified lines464748495051521 unmodified line54555657585960616263646566676845 unmodified lines**`timeout`** (`float`): The maximum time taken to produce a prediction before it is considered a "timeout". The default value is `3.0` (i.e. 3 seconds).In addition, this metric supports three additional arguments, specifying which imports should be made available, and controlling other apsects of `RestrictedPython` behavior:**`use_safe_builtins`** (`bool`): Whether or not to allow the usage of [`RestrictedPython.safe_builtins`](https://github.com/zopefoundation/RestrictedPython/blob/c31c133844ac2308f5cc930e934a7227a2a6a77b/src/RestrictedPython/Guards.py#L23), defaults to True1 unmodified line**`use_utility_builtins`** (`bool`): Whether or not to allow the usage of [`RestrictedPython.utility_builtins`](https://github.com/zopefoundation/RestrictedPython/blob/c31c133844ac2308f5cc930e934a7227a2a6a77b/src/RestrictedPython/Utilities.py#L19), which includes the `string`, `math`, `random`, and `set` packages, among others. Defaults to True.**`additional_globals`** (`Dict[str, Any] | None`): Any additional `globals` to make available to the code. Defaults to None.**`additional_locals`** (`Dict[str, Any] | None`): Any additional `locals` to make available to the code. Defaults to None.**`allowed_imports`** (`List[str] | None`): A list of allowed imports. Defaults to None.As the new arguments are optional, this could be used as a drop-in replacement for `code_eval`.Additionally, this metric sets several different `globals` if they are not provided as additional globals. The full list of globals set is: `__metaclass__, __name__, _getiter_, _iter_unpack_sequence_, _getitem_, getattr, _write_, _inplacevar_`. See the code for additional details.### Output Values
18 unmodified lines1920212223242526272829303 unmodified lines34353637383925 unmodified lines65666768697077 unmodified lines14814915015115215315411 unmodified lines16616716816917017117238 unmodified lines2112122132142152162174 unmodified lines2222232242252262272289 unmodified lines23823924024124224324424519 unmodified lines265266267268269270271272273274153 unmodified lines42842943043118 unmodified linesimport contextlibimport faulthandlerimport itertoolsimport ioimport multiprocessingimport osimport platformimport signalimport tempfilefrom collections import Counter, defaultdictfrom concurrent.futures import ThreadPoolExecutor, as_completed3 unmodified linesimport datasetsimport numpy as npfrom RestrictedPython import compile_restricted, safe_builtins, limited_builtins, utility_builtins# TODO: Add BibTeX citation25 unmodified linesuse_safe_builtins: a bool indicating whether to use the `RestrictedPython.safe_builtins`use_limited_builtins: a bool indicating whether to use the `RestrictedPython.limited_builtins`use_utility_builtins: a bool indicating whether to use the `RestrictedPython.utility_builtins`Returns:pass_at_k: dict with pass rates for each kresults: dict with granular results of each unittest77 unmodified lines)def _compute(self, predictions, references, k=[1, 10, 100], num_workers=4, timeout=3.0,use_safe_builtins: bool = True, use_limited_builtins: bool = True, use_utility_builtins: bool = True):"""Returns the scores"""if os.getenv("HF_ALLOW_CODE_EVAL", 0) != "1":11 unmodified linesfor task_id, (candidates, test_case) in enumerate(zip(predictions, references)):for candidate in candidates:test_program = candidate + "\n" + test_caseargs = (test_program, timeout, task_id, completion_id[task_id], use_safe_builtins, use_limited_builtins, use_utility_builtins)future = executor.submit(_check_correctness, *args)futures.append(future)completion_id[task_id] += 138 unmodified linesdef _check_correctness(check_program, timeout, task_id, completion_id,use_safe_builtins: bool = True, use_limited_builtins: bool = True, use_utility_builtins: bool = True):"""Evaluates the functional correctness of a completion by running the testsuite provided in the problem.4 unmodified linesmanager = multiprocessing.Manager()result = manager.list()p = multiprocessing.Process(target=_unsafe_execute, args=(check_program, result, timeout, use_safe_builtins, use_limited_builtins, use_utility_builtins))p.start()p.join(timeout=timeout + 1)if p.is_alive():9 unmodified linescompletion_id=completion_id,)def _unsafe_execute(check_program, result, timeout,use_safe_builtins: bool = True, use_limited_builtins: bool = True, use_utility_builtins: bool = True):with create_tempdir():19 unmodified linesbuiltins.update(utility_builtins)exec_globals = {'__builtins__': builtins}with swallow_io():with time_limit(timeout):byte_code = compile_restricted(check_program, filename="<model output>", mode="exec")exec(byte_code, exec_globals, None)result.append("passed")except TimeoutException:result.append("timed out")153 unmodified linessys.modules["joblib"] = None # type: ignoresys.modules["resource"] = None # type: ignoresys.modules["psutil"] = None # type: ignoresys.modules["tkinter"] = None # type: ignore18 unmodified lines1920212223242526272829303132333 unmodified lines373839404142434425 unmodified lines7071727374757677787977 unmodified lines15715815916016116216316416511 unmodified lines17717817918018118218318418518618738 unmodified lines2262272282292302312322332344 unmodified lines2392402412422432442452462472482492509 unmodified lines26026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429519 unmodified lines315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356153 unmodified lines51051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063118 unmodified linesimport contextlibimport faulthandlerimport itertoolsimport importlibimport ioimport multiprocessingimport osimport platformimport signalimport tempfileimport typesfrom typing import Optional, Dict, List, Anyfrom collections import Counter, defaultdictfrom concurrent.futures import ThreadPoolExecutor, as_completed3 unmodified linesimport datasetsimport numpy as npfrom RestrictedPython import compile_restricted, safe_builtins, limited_builtins, utility_builtinsfrom RestrictedPython.Eval import default_guarded_getiter, default_guarded_getitemfrom RestrictedPython.Guards import guarded_iter_unpack_sequence, safer_getattr# TODO: Add BibTeX citation25 unmodified linesuse_safe_builtins: a bool indicating whether to use the `RestrictedPython.safe_builtins`use_limited_builtins: a bool indicating whether to use the `RestrictedPython.limited_builtins`use_utility_builtins: a bool indicating whether to use the `RestrictedPython.utility_builtins`additional_globals: a optional dict of additional globals to pass to the RestrictedPython interpreteradditional_locals: a optional dict of additional locals to pass to the RestrictedPython interpreterallowed_imports: an optional list of string, modules the tested code is allowed to importReturns:pass_at_k: dict with pass rates for each kresults: dict with granular results of each unittest77 unmodified lines)def _compute(self, predictions, references, k=[1, 10, 100], num_workers=4, timeout=3.0,use_safe_builtins: bool = True, use_limited_builtins: bool = True, use_utility_builtins: bool = True,additional_globals: Optional[Dict[str, Any]] = None, additional_locals: Optional[Dict[str, Any]] = None,allowed_imports: Optional[List[str]] = None):"""Returns the scores"""if os.getenv("HF_ALLOW_CODE_EVAL", 0) != "1":11 unmodified linesfor task_id, (candidates, test_case) in enumerate(zip(predictions, references)):for candidate in candidates:test_program = candidate + "\n" + test_caseargs = (test_program, timeout, task_id, completion_id[task_id],use_safe_builtins, use_limited_builtins, use_utility_builtins,additional_globals, additional_locals, allowed_imports)future = executor.submit(_check_correctness, *args)futures.append(future)completion_id[task_id] += 138 unmodified linesdef _check_correctness(check_program, timeout, task_id, completion_id,use_safe_builtins: bool = True, use_limited_builtins: bool = True, use_utility_builtins: bool = True,additional_globals: Optional[Dict[str, Any]] = None, additional_locals: Optional[Dict[str, Any]] = None,allowed_imports: Optional[List[str]] = None):"""Evaluates the functional correctness of a completion by running the testsuite provided in the problem.4 unmodified linesmanager = multiprocessing.Manager()result = manager.list()args = (check_program, result, timeout,use_safe_builtins, use_limited_builtins, use_utility_builtins,additional_globals, additional_locals, allowed_imports)p = multiprocessing.Process(target=_unsafe_execute, args=args)p.start()p.join(timeout=timeout + 1)if p.is_alive():9 unmodified linescompletion_id=completion_id,)class AllowListImporter:def __init__(self, allowed_imports: List[str]):self.allowed_imports = allowed_importsdef __call__(self, name, globals=None, locals=None, fromlist=(), level=0):if name.startswith('.'):raise ImportError("Relative imports are not allowed.")if '.' in name:package_name, _ = name.split('.', 1)else:package_name = nameif package_name in self.allowed_imports:return importlib.__import__(name, globals, locals, fromlist, level)def _default_write_(obj):if isinstance(obj, types.ModuleType):raise ValueError("Modules are not allowed in to be written to.")return objdef _unsafe_execute(check_program, result, timeout,use_safe_builtins: bool = True, use_limited_builtins: bool = True, use_utility_builtins: bool = True,additional_globals: Optional[Dict[str, Any]] = None, additional_locals: Optional[Dict[str, Any]] = None,allowed_imports: Optional[List[str]] = None):with create_tempdir():19 unmodified linesbuiltins.update(utility_builtins)exec_globals = {'__builtins__': builtins}exec_globals.update(additional_globals or {})if allowed_imports is not None:if '__import__' in exec_globals['__builtins__']:raise ValueError("Cannot specify allowed_imports when __import__ is in additional_globals.")exec_globals['__builtins__']['__import__'] = AllowListImporter(allowed_imports)if '__metaclass__' not in exec_globals:exec_globals['__metaclass__'] = type # type: ignoreif '__name__' not in exec_globals:exec_globals['__name__'] = '__main__' # type: ignoreif '_getiter_' not in exec_globals:exec_globals['_getiter_'] = default_guarded_getiter # type: ignoreif '_iter_unpack_sequence_' not in exec_globals:exec_globals['_iter_unpack_sequence_'] = guarded_iter_unpack_sequence # type: ignoreif '_getitem_' not in exec_globals:exec_globals['_getitem_'] = default_guarded_getitem # type: ignoreif 'getattr' not in exec_globals:exec_globals['getattr'] = safer_getattr # type: ignoreif '_write_' not in exec_globals:exec_globals['_write_'] = _default_write_ # type: ignoreif '_inplacevar_' not in exec_globals:exec_globals['_inplacevar_'] = protected_inplacevar # type: ignorewith swallow_io():with time_limit(timeout):byte_code = compile_restricted(check_program, filename="<model output>", mode="exec")exec(byte_code, exec_globals, additional_locals)result.append("passed")except TimeoutException:result.append("timed out")153 unmodified linessys.modules["joblib"] = None # type: ignoresys.modules["resource"] = None # type: ignoresys.modules["psutil"] = None # type: ignoresys.modules["tkinter"] = None # type: ignore"""Borrowed implementation of _inplacevar_ from the Zope Foundations's AccessControl modulehttps://github.com/zopefoundation/AccessControl/blob/f9ae58816f0712eb6ea97459b4ccafbf4662d9db/src/AccessControl/ZopeGuards.py#L530"""valid_inplace_types = (list, set)inplace_slots = {'+=': '__iadd__','-=': '__isub__','*=': '__imul__','/=': (1 / 2 == 0) and '__idiv__' or '__itruediv__','//=': '__ifloordiv__','%=': '__imod__','**=': '__ipow__','<<=': '__ilshift__','>>=': '__irshift__','&=': '__iand__','^=': '__ixor__','|=': '__ior__',}def __iadd__(x, y):x += yreturn xdef __isub__(x, y):x -= yreturn xdef __imul__(x, y):x *= yreturn xdef __idiv__(x, y):x /= yreturn xdef __ifloordiv__(x, y):x //= yreturn xdef __imod__(x, y):x %= yreturn xdef __ipow__(x, y):x **= yreturn xdef __ilshift__(x, y):x <<= yreturn xdef __irshift__(x, y):x >>= yreturn xdef __iand__(x, y):x &= yreturn xdef __ixor__(x, y):x ^= yreturn xdef __ior__(x, y):x |= yreturn xinplace_ops = {'+=': __iadd__,'-=': __isub__,'*=': __imul__,'/=': __idiv__,'//=': __ifloordiv__,'%=': __imod__,'**=': __ipow__,'<<=': __ilshift__,'>>=': __irshift__,'&=': __iand__,'^=': __ixor__,'|=': __ior__,}def protected_inplacevar(op, var, expr):"""Do an inplace operationIf the var has an inplace slot, then disallow the operationunless the var an instance of ``valid_inplace_types``."""if hasattr(var, inplace_slots[op]) and \not isinstance(var, valid_inplace_types):try:cls = var.__class__except AttributeError:cls = type(var)raise TypeError("Augmented assignment to %s objects is not allowed"" in untrusted code" % cls.__name__)return inplace_ops[op](var, expr)
README.md+10-2
restrictedpython_code_eval.py+207-7