/ Модель

Характеристики

Лицензия
MIT
Библиотека
pytorch
Опубликована
22 окт 2026

Zahhak-snakehandler

Обучение с подкреплением3 профессии

Агент Double DQN на PyTorch, который обучается играть в «Змейку» и подходит для экспериментов с обучением с подкреплением.

0скачиваний за 30 дней0лайковвеса обновлены23 окт 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Zahhak-snakehandler — агент глубокого обучения с подкреплением на PyTorch, разработанный kheradafrouz для игры в «Змейку». Он обучается выбирать действия в пользовательской среде игры с помощью Double DQN, буфера воспроизведения опыта и целевой сети. Политическая сеть оценивает Q-значения для трёх действий: двигаться прямо, повернуть направо или налево; состояние задаётся 14 признаками опасности, направления движения и положения еды.

Проект подходит для изучения и демонстрации Double DQN, исследования наград и стратегий исследования, а также сравнения обученной жадной политики со случайным выбором действий. Реализованы обучение с визуальной панелью Pygame или без неё, возобновление по контрольным точкам и оценка в отдельной среде. Поддерживаются CPU, CUDA и Apple Silicon MPS; стандартная сеть имеет два скрытых слоя по 128 нейронов, размеры слоёв настраиваются.

Модель специализирована на описанной среде «Змейки» и не предназначена для управления реальными системами или обработки естественного языка. Качество обучения зависит от наград, гиперпараметров, случайного зерна и длительности обучения; в карточке нет фиксированных результатов бенчмарка. Лицензия — MIT.

Сценарии применения

  • обучение агента для игры в «Змейку»
  • изучение алгоритма Double DQN на игровом примере
  • эксперименты с функцией награды и исследованием среды
  • сравнение обученной политики со случайным выбором действий

Ограничения

Агент рассчитан на пользовательскую среду игры «Змейка»; качество зависит от конфигурации обучения и не гарантирует конкретный результат. Фиксированные показатели бенчмарка не заявлены.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Zahhak-snakehandler

A Deep Reinforcement Learning Agent for Snake — From Scratch

Zahhak-snakehandler is a PyTorch-based reinforcement learning project that learns to play Snake through reward-driven interaction with its environment. It implements Double Deep Q-Network (Double DQN), experience replay, a target network, and configurable training on CPU, NVIDIA CUDA GPUs, and Apple Silicon MPS.

The project includes a live Pygame dashboard, headless training, resumable checkpoints, and a dedicated evaluation workflow comparing a greedy policy against a random-action baseline.

Source code: kheradafrouz/Zahhak-snakehandler

Model Details

PropertyDescription
Model nameZahhak-snakehandler
Model typeDeep Reinforcement Learning Agent
AlgorithmDouble Deep Q-Network (Double DQN)
FrameworkPyTorch 2.x
EnvironmentCustom Snake environment
Observation space14 binary-valued features
Action space3 relative actions
Network architectureMultilayer Perceptron (MLP)
Default hidden layers128, 128
Default optimizerAdam
Default learning rate0.001
Default discount factor0.95
LicenseMIT

Intended Use

This agent is intended for:

  • Learning and experimenting with deep reinforcement learning.
  • Demonstrating Double DQN and experience replay.
  • Studying reward shaping and exploration strategies.
  • Comparing greedy policy performance with a random baseline.
  • Experimenting with training speed across CPU and GPU devices.
  • Educational projects involving game-playing agents.

This project is designed for the Snake game environment. It is not a general-purpose language model or a model for real-world autonomous control.

Architecture

The agent uses a feed-forward neural network to estimate action values, Q(s, a), for the three available actions.

The implementation includes:

  • Policy network: Selects actions and estimates Q-values.
  • Target network: Provides more stable target estimates during learning.
  • Experience replay buffer: Samples past transitions for training.
  • Double DQN: Uses the policy network to select the next action and the target network to evaluate it.
  • Huber loss: Reduces sensitivity to large temporal-difference errors.
  • Gradient clipping: Helps control large gradients.
  • Adam optimizer: Updates the policy network parameters.

The default network has two hidden layers of 128 units each, with ReLU activations. Hidden layer sizes are configurable.

Observation Space

The agent receives a 14-feature state representation:

Feature groupNumber of featuresDescription
Danger indicators6Collision danger one and two cells ahead for straight, right, and left directions
Heading4One-hot encoding of the snake's current direction
Food direction4Relative food position: left, right, up, and down
Total14Binary-valued features

The observation is a compact representation of local danger, orientation, and food direction rather than a raw image of the board.

Action Space

The agent chooses among three relative actions:

  1. Move straight.
  2. Turn right.
  3. Turn left.

A direct 180-degree reversal is excluded by the environment's action design.

Reward Function

The default reward configuration is:

EventReward
Eating food+10.0
Death-10.0
Starvation timeout-10.0
Moving closer to food+0.1
Moving farther from food-0.15

The environment also terminates an episode after 100 times the current snake length in steps without eating food, preventing indefinite loops.

These rewards encourage food collection and survival while discouraging collisions, starvation, and movement away from food.

Training Configuration

Default training settings:

ParameterDefault
Grid size15 × 15
Hidden layer sizes128, 128
Learning rate0.001
Discount factor (gamma)0.95
Batch size64
Replay buffer capacity50,000
Learning frequencyEvery 2 environment steps
Target network synchronizationEvery 500 gradient steps
Initial epsilon1.0
Minimum epsilon0.02
Epsilon decay0.997 per episode
Random seed42
Default training duration3,000 episodes

The project also provides a GPU preset with larger hidden layers, batches, and replay buffer capacity.

All settings can be adjusted through the project configuration and command-line interface.

Exploration Strategy

The agent uses epsilon-greedy exploration.

At the beginning of training, the agent explores extensively with epsilon set to 1.0. Epsilon decays by a factor of 0.997 per episode until it reaches the minimum value of 0.02.

This allows the agent to gradually shift from random exploration toward actions selected by its learned Q-values.

Evaluation

Zahhak-snakehandler includes a separate evaluation module that compares:

  • A greedy policy with epsilon = 0.
  • A random-action baseline.

Evaluation runs in a separate seeded environment and reports metrics such as average score, maximum score, and average survival length.

No fixed benchmark results are claimed in this model card because performance can vary with random seeds, training duration, hardware, and software versions.

For reproducible comparisons, evaluate multiple seeds and report the training configuration alongside the results.

Evaluation instructions and implementation: GitHub repository

Hardware and Performance

Supported compute backends:

  • CPU: Standard PyTorch installation.
  • NVIDIA CUDA: GPU training with a compatible PyTorch CUDA build and NVIDIA driver.
  • Apple Silicon MPS: Supported where the installed PyTorch version and device provide the required functionality.

The GPU preset uses hidden layers of 256 units, a batch size of 512, and a replay buffer capacity of 200,000.

A GPU is not guaranteed to be faster for this workload. The network is relatively small, and action selection often processes one state at a time. Performance should be measured on the target machine.

Limitations

  • The agent is designed for the project's custom Snake environment.
  • Learning quality depends on the reward design, hyperparameters, random seed, and training duration.
  • Training reward does not necessarily reflect the performance of the final greedy policy.
  • Successful execution does not guarantee successful learning.
  • The project does not claim a particular score or level of performance without measured evaluation results.
  • Checkpoints must be loaded with compatible model architecture and appropriate software dependencies.

Intended Audience

This project is suitable for students, researchers, and developers exploring reinforcement learning, PyTorch, Q-learning, and game-playing agents.

It is intended for educational and experimental use rather than safety-critical applications.

Usage and Installation

The complete installation instructions, dependencies, training commands, and dashboard controls are documented in the source repository.

Repository: https://github.com/kheradafrouz/Zahhak-snakehandler

Clone and install the project:

git clone https://github.com/kheradafrouz/Zahhak-snakehandler.git
cd Zahhak-snakehandler

python -m venv .venv
source .venv/bin/activate

pip install -r requirements.txt

Train the agent without rendering:

python -m zahhak_snakehandler.train --episodes 3000

Launch the dashboard:

python -m zahhak_snakehandler.main

Evaluate a saved checkpoint:

python -m zahhak_snakehandler.evaluate \
  --model checkpoints/Zahhak-snakehandler_best.pt \
  --episodes 200

For CUDA-specific installation and commands, see the repository's CPU vs GPU section.

Checkpoints

The training system supports resumable checkpoints that can store:

  • Policy and target network weights.
  • Optimizer state.
  • Exploration parameter (epsilon).
  • Replay buffer.
  • Training metric history.

Checkpoints are written atomically to reduce the risk of incomplete files during saving.

The commands and exact checkpoint formats are documented in the source repository.

Reproducibility

The project supports configurable random seeds and exposes its training hyperparameters through its configuration module.

For reproducible experiments:

  1. Record the software versions and hardware.
  2. Record the seed and training configuration.
  3. Evaluate the greedy policy separately from training.
  4. Compare against the random-action baseline.
  5. Report results across multiple seeds.

Training Data

The agent learns through interactions with the Snake environment using rewards and state transitions. It does not require a conventional labeled training dataset.

The environment rules and reward implementation are available in snake_env.py.

Ethical Considerations

This is a game-playing research and educational project with no intended direct impact on people. Its learned behavior is specific to the environment and reward function used during training.

Results should not be generalized to unrelated environments without further training and evaluation.

Citation

If you use this project in research or educational work, cite the repository:

@software{zahhak_snakehandler,
  title = {Zahhak-snakehandler},
  author = {Kheradafrouz},
  url = {https://github.com/kheradafrouz/Zahhak-snakehandler},
  license = {MIT}
}

Links

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · pytorch

Нельзя запустить

RL-агенты не запускаются как сервис инференса.

Ревизия весов
56a97f8

0 моделей