Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions game_first_exam/benchmarks/game2048/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Gymnasium 2048 native integration

This directory adds a thin adapter, trusted schema, metric validation and source provenance for the MIT-licensed
[`gymnasium-2048`](https://github.com/Quentin18/gymnasium-2048) environment. Frozen Harbor tasks, a game suite and
benchmark registration are intentionally deferred.

## Frozen native profile

| Area | Implementation |
|---|---|
| Upstream | `gymnasium-2048==0.1.2`, tag `v0.1.2`, commit recorded in `SOURCE.json` |
| Environment | `gymnasium_2048/TwentyFortyEight-v0`, native 4x4 board and 16 one-hot exponent channels |
| Observation | Native 400x460 RGB rendering of the board and cumulative score, transported as PNG |
| Actions | All four native actions: up, right, down and left |
| Randomness | Native `reset(seed=...)`; legal moves spawn a 2 tile with probability 0.9 or a 4 tile with probability 0.1 |
| Reward | Native merge score increment; cumulative native reward is the standard 2048 score |
| End | Native termination only when no legal move remains; future tasks must also set a public action cap |
| Metrics | Native score, maximum tile, valid/invalid moves and a non-terminating 2048-tile success label |

## Isolation

Only `image_png_base64` is returned to the agent. The upstream one-hot observation and `info` object are deliberately
not forwarded because `info["board"]` contains the exact internal board. The board exponent array, RNG state, native
score, move legality and counters remain in the simulator and contribute to `fingerprint()` for audit integrity.
Rendering is cached after reset and every accepted action, so `observe()`, `spec()`, `metrics()` and `frame()` are
read-only and cannot advance RNG.

No task, solution, reference trajectory or container stack is included. A later task PR must separately verify the
main/simulator/verifier mounts, agent network policy and a no-network verifier before the benchmark is registered.

## Validation

`test_game2048_contract.py` exercises the shared service, schema, metric validator and public isolation with a
deterministic native-shaped engine double. `test_game2048_native.py` compares the adapter to direct calls into the
pinned upstream environment across seeds, every action, trajectories, rewards, RGB frames and internal state.
10 changes: 10 additions & 0 deletions game_first_exam/benchmarks/game2048/SOURCE.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"project": "gymnasium-2048",
"repository": "https://github.com/Quentin18/gymnasium-2048",
"tag": "v0.1.2",
"commit": "b686d2a82a347066ffa8a82f6f4f57ac44deb5dc",
"license": "MIT",
"pypi": "https://pypi.org/project/gymnasium-2048/0.1.2/",
"wheel": "gymnasium_2048-0.1.2-py3-none-any.whl",
"wheel_sha256": "d906d6757a06553c80709e4a4aa06d47ee6ad053e9506f6ce5c6c63d3e3d8688"
}
151 changes: 151 additions & 0 deletions game_first_exam/benchmarks/game2048/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
"""Gymnasium 2048 backend with native RGB rendering and scoring."""
import importlib.metadata
import numbers

import gymnasium as gym
import gymnasium_2048 # noqa: F401 - registers the environment
import numpy as np

from contracts import Capabilities, Transition
from encoding import png, state_hash


ACTIONS = {'UP': 0, 'RIGHT': 1, 'DOWN': 2, 'LEFT': 3}
INFO_FIELDS = {'board', 'step_score', 'total_score', 'max', 'is_legal', 'illegal_count'}


def make_native_env(instance):
return gym.make(
instance['env_id'], render_mode='rgb_array',
size=instance['board_size'], max_pow=instance['native_max_power'],
)


class Adapter:
def __init__(self, instance, assets=None):
self.instance = instance
for name, version in instance['engine_versions'].items():
if importlib.metadata.version(name) != version:
raise ValueError('2048 dependency version mismatch: ' + name)
self.env = make_native_env(instance)
try:
native = self.env.unwrapped
if (native.action_space.n != 4
or native.observation_space.shape != (
instance['board_size'], instance['board_size'],
instance['native_max_power'])):
raise ValueError('native 2048 spaces changed')
observation, info = self.env.reset(seed=instance['seed'])
self._validate_native(observation, info, initial=True)
self.image = self._render()
except Exception:
self.env.close()
raise
self.steps = 0
self.total_return = 0.0
self.ended = False

def _validate_native(self, observation, info, initial=False):
native = self.env.unwrapped
size = self.instance['board_size']
if (not isinstance(observation, np.ndarray)
or observation.shape != (size, size, self.instance['native_max_power'])
or observation.dtype != np.uint8
or not np.all(observation.sum(axis=2) == 1)
or not np.array_equal(np.argmax(observation, axis=2), native.board)):
raise ValueError('native 2048 observation changed')
if set(info) != INFO_FIELDS or not np.array_equal(info['board'], native.board):
raise ValueError('native 2048 info changed')
scalar_fields = ('step_score', 'total_score', 'max', 'illegal_count')
if any(isinstance(info[key], bool) or not isinstance(info[key], numbers.Integral)
for key in scalar_fields) or not isinstance(info['is_legal'], bool):
raise ValueError('native 2048 info types changed')
if (int(info['total_score']) != int(native.total_score)
or int(info['step_score']) != int(native.step_score)
or int(info['max']) != int(native.board.max())
or int(info['illegal_count']) != int(native.illegal_count)
or info['is_legal'] is not native.is_legal):
raise ValueError('native 2048 info disagrees with engine state')
if initial and ((native.board != 0).sum() != 2
or native.total_score != 0 or native.illegal_count != 0):
raise ValueError('native 2048 initial state changed')

def _render(self):
image = self.env.render()
if (not isinstance(image, np.ndarray)
or list(image.shape) != self.instance['native_render_shape']
or image.dtype != np.uint8):
raise ValueError('native 2048 RGB rendering changed')
return image.copy()

def spec(self):
return {
'adapter_version': '1.0.0',
'capabilities': Capabilities(images=True, action_mode='enum').to_dict(),
'action_schema': {'type': 'string', 'enum': list(ACTIONS)},
'action_indices': dict(ACTIONS),
'observation': ('Native RGB rendering of the 4x4 board and cumulative score; '
'PNG transport only.'),
'goal': 'Maximize the native merge score and build the largest possible tile.',
}

def observe(self):
return {'image_png_base64': png(self.image)}

def step(self, action):
if self.ended:
raise ValueError('episode closed')
if action not in ACTIONS:
raise ValueError('unknown 2048 action')
observation, reward, terminated, truncated, info = self.env.step(ACTIONS[action])
if isinstance(reward, bool) or not isinstance(reward, numbers.Integral) or reward < 0:
raise ValueError('native 2048 reward changed')
if truncated:
raise ValueError('unexpected native 2048 truncation')
self._validate_native(observation, info)
reward = int(reward)
if reward != int(info['step_score']):
raise ValueError('native 2048 reward disagrees with step score')
self.steps += 1
self.total_return += reward
if self.total_return != int(info['total_score']):
raise ValueError('native 2048 cumulative score changed')
self.image = self._render()
self.ended = bool(terminated)
return Transition(float(reward), bool(terminated), False)

def success(self):
return int(self.env.unwrapped.board.max()) >= self.instance['target_power']

def metrics(self):
native = self.env.unwrapped
maximum = int(native.board.max())
invalid = int(native.illegal_count)
return {
'target_reached': int(self.success()),
'native_score': int(native.total_score),
'max_tile': 2 ** maximum,
'valid_moves': self.steps - invalid,
'invalid_moves': invalid,
'native_return': self.total_return,
}

def fingerprint(self):
native = self.env.unwrapped
return state_hash({
'board': native.board,
'rng': native.np_random.bit_generator.state,
'step_score': native.step_score,
'total_score': native.total_score,
'is_legal': native.is_legal,
'illegal_count': native.illegal_count,
'steps': self.steps,
'return': self.total_return,
'ended': self.ended,
})

def frame(self):
return self.image.copy()

def close(self):
self.env.close()
39 changes: 39 additions & 0 deletions game_first_exam/benchmarks/game2048/instance_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Trusted stdlib-only schema for the native Gymnasium 2048 profile."""
from config_schema import validate_engine_versions

SCHEMA_VERSION = '1.0.0'
BENCHMARK = 'game2048'
FIELDS = {'engine_versions', 'board_size', 'native_max_power',
'native_render_shape', 'target_power'}
METRICS = {'target_reached', 'native_score', 'max_tile', 'valid_moves',
'invalid_moves', 'native_return'}
PROFILES = {'native-rgb-board-score-v1'}
REDUCERS = {('family_macro', '1.0.0')}
ENGINE_VERSIONS = {
'gymnasium-2048': '0.1.2',
'gymnasium': '1.3.0',
'numpy': '1.26.4',
'pygame': '2.6.1',
}


def validate(value):
validate_engine_versions(value['engine_versions'], ENGINE_VERSIONS)
if (value['env_id'] != 'gymnasium_2048/TwentyFortyEight-v0'
or value['family'] != '2048-classic'):
raise ValueError('unsupported 2048 environment/family')
if value['board_size'] != 4 or value['native_max_power'] != 16:
raise ValueError('unsupported native 2048 board profile')
if value['native_render_shape'] != [460, 400, 3]:
raise ValueError('unsupported native 2048 render profile')
if value['target_power'] != 11:
raise ValueError('the supported target is the native 2048 tile')
if type(value['max_steps']) is not int or not 1 <= value['max_steps'] <= 10000:
raise ValueError('2048 requires a public action cap in [1, 10000]')
if value['capabilities'] != {'images': True, 'action_mode': 'enum',
'timing': 'action-stepped', 'native_truncation': False}:
raise ValueError('unsupported 2048 capabilities')
if value['metric_spec'] != {'primary': 'native_score', 'reducer': 'family_macro',
'reducer_version': '1.0.0',
'success_label': '2048_tile_reached'}:
raise ValueError('unsupported 2048 scoring profile')
35 changes: 35 additions & 0 deletions game_first_exam/benchmarks/game2048/metric_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Validate native 2048 score, tile and move-count relationships."""
import math


def validate_metrics(final, instance):
metrics = final['metrics']
expected = {'target_reached', 'native_score', 'max_tile', 'valid_moves',
'invalid_moves', 'native_return'}
if set(metrics) != expected:
raise ValueError('wrong 2048 metric fields')
for key in ('target_reached', 'native_score', 'max_tile',
'valid_moves', 'invalid_moves'):
if type(metrics[key]) is not int:
raise ValueError('2048 integer metric has wrong type: ' + key)
score, maximum = metrics['native_score'], metrics['max_tile']
valid, invalid = metrics['valid_moves'], metrics['invalid_moves']
if score < 0 or score % 4 or valid < 0 or invalid < 0:
raise ValueError('invalid 2048 score or move count')
if (maximum < 2 or maximum > 2 ** (instance['native_max_power'] - 1)
or maximum & (maximum - 1)):
raise ValueError('invalid 2048 maximum tile')
if valid + invalid != final['steps']:
raise ValueError('2048 move counts disagree with accepted steps')
if not isinstance(metrics['native_return'], (int, float)) or isinstance(
metrics['native_return'], bool) or not math.isfinite(metrics['native_return']):
raise ValueError('invalid 2048 native return')
if metrics['native_return'] != score or final['return'] != score:
raise ValueError('2048 score disagrees with native return')
reached = int(maximum >= 2 ** instance['target_power'])
if metrics['target_reached'] != reached:
raise ValueError('2048 target flag disagrees with maximum tile')
if final['success'] != (bool(reached) and not final['sim_error']):
raise ValueError('2048 success disagrees with target tile')
if final['steps'] == 0 and (score or valid or invalid or maximum > 4):
raise ValueError('2048 progress without an action')
10 changes: 10 additions & 0 deletions game_first_exam/benchmarks/game2048/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
cloudpickle==3.1.3
Farama-Notifications==0.0.6
gymnasium==1.3.0
gymnasium-2048==0.1.2
ImageIO==2.37.0
imageio-ffmpeg==0.6.0
numpy==1.26.4
pillow==10.4.0
pygame==2.6.1
typing_extensions==4.16.0
10 changes: 10 additions & 0 deletions game_first_exam/images/game2048-files/FILES.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"image": "ghcr.io/mll-lab-nu/efe:game2048-files-0.1.0@sha256:593f0e1acddbaa5ded9063240faae3f503a7fbd47796e881353d49313e3bcd5b",
"source": "game_first_exam/benchmarks/game2048",
"files": {
"adapter.py": "0847f01610056431292e0fde192c4fe27ba7a12246bd02e205743a596372918c",
"metric_rules.py": "16cf8351b56e9e6c81d0205224ecd0ba5d190a3f7039177eb410b4aff7a7a5b6",
"requirements.txt": "e9a56545e89778489fd2d5ee1922bb85cec310b2b7620178db6f31871988340f",
"instance_schema.py": "24f1dd3940edb74c4ea23527bf53004a7285f114446b7c402cba29f7cc0877d7"
}
}
4 changes: 4 additions & 0 deletions game_first_exam/images/game2048-files/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# game2048-files

Files-only image for the Gymnasium 2048 adapter. Build locally with
`python scripts/files_image.py build game2048-files`. The pinned image is not published by this local integration.
1 change: 1 addition & 0 deletions game_first_exam/images/game2048-files/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.1.0
7 changes: 7 additions & 0 deletions game_first_exam/tests/envs/game2048.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db
ENV PYTHONUNBUFFERED=1
RUN apt-get update && apt-get install -y --no-install-recommends libglib2.0-0 libgl1 ca-certificates fonts-dejavu-core && rm -rf /var/lib/apt/lists/*
COPY game_first_exam/tests/envs/locks/game2048.txt /requirements.txt
RUN pip install --no-cache-dir --no-deps -r /requirements.txt
RUN pip check
WORKDIR /repo
10 changes: 10 additions & 0 deletions game_first_exam/tests/envs/locks/game2048.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
cloudpickle==3.1.3
Farama-Notifications==0.0.6
gymnasium==1.3.0
gymnasium-2048==0.1.2
ImageIO==2.37.0
imageio-ffmpeg==0.6.0
numpy==1.26.4
pillow==10.4.0
pygame==2.6.1
typing_extensions==4.16.0
Loading