Upload 84 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .env.example +1 -0
- .gitignore +306 -0
- README.md +31 -0
- algo/README.md +6 -0
- algo/__init__py +0 -0
- algo/moe_trainer.py +90 -0
- algo/supervised.py +0 -0
- algo/trainer.py +85 -0
- benchmarks/README.md +7 -0
- benchmarks/config.py +43 -0
- benchmarks/config_ui.py +347 -0
- benchmarks/configs.json +122 -0
- benchmarks/models/__pycache__/moe_rope_vanilla_decoder_transformer.cpython-313.pyc +0 -0
- benchmarks/models/__pycache__/moe_vanilla_decoder_transformer.cpython-313.pyc +0 -0
- benchmarks/models/__pycache__/rope_vanilla_decoder_transformer.cpython-313.pyc +0 -0
- benchmarks/models/__pycache__/vanilla_decoder_transformer.cpython-313.pyc +0 -0
- benchmarks/models/moe_rope_vanilla_decoder_transformer.py +66 -0
- benchmarks/models/moe_vanilla_decoder_transformer.py +66 -0
- benchmarks/models/rope_vanilla_decoder_transformer.py +38 -0
- benchmarks/models/vanilla_decoder_transformer.py +38 -0
- benchmarks/registry.py +170 -0
- benchmarks/results.py +70 -0
- benchmarks/run.py +333 -0
- benchmarks/tasks/__init__.py +8 -0
- benchmarks/tasks/__pycache__/aggregation.cpython-313.pyc +0 -0
- benchmarks/tasks/__pycache__/composition.cpython-313.pyc +0 -0
- benchmarks/tasks/__pycache__/counting.cpython-313.pyc +0 -0
- benchmarks/tasks/__pycache__/hierarchical.cpython-313.pyc +0 -0
- benchmarks/tasks/__pycache__/long_range.cpython-313.pyc +0 -0
- benchmarks/tasks/__pycache__/rule_extraction.cpython-313.pyc +0 -0
- benchmarks/tasks/__pycache__/short_range.cpython-313.pyc +0 -0
- benchmarks/tasks/__pycache__/state.cpython-313.pyc +0 -0
- benchmarks/tasks/aggregation.py +142 -0
- benchmarks/tasks/composition.py +174 -0
- benchmarks/tasks/counting.py +136 -0
- benchmarks/tasks/hierarchical.py +237 -0
- benchmarks/tasks/long_range.py +200 -0
- benchmarks/tasks/rule_extraction.py +152 -0
- benchmarks/tasks/short_range.py +141 -0
- benchmarks/tasks/state.py +154 -0
- deploy/README.md +4 -0
- module/README.md +4 -0
- module/__init__.py +7 -0
- module/transformers/__init__.py +0 -0
- module/transformers/__pycache__/__init__.cpython-313.pyc +0 -0
- module/transformers/moe/__init__.py +0 -0
- module/transformers/moe/__pycache__/__init__.cpython-313.pyc +0 -0
- module/transformers/moe/__pycache__/moe.cpython-313.pyc +0 -0
- module/transformers/moe/__pycache__/moe_rope_transformer_block.cpython-313.pyc +0 -0
- module/transformers/moe/__pycache__/transformer_block.cpython-313.pyc +0 -0
.env.example
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
MLFLOW_TRACKING_URI=https://example.mlflow.server:5000
|
.gitignore
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[codz]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
# C extensions
|
| 7 |
+
*.so
|
| 8 |
+
|
| 9 |
+
# Distribution / packaging
|
| 10 |
+
.Python
|
| 11 |
+
build/
|
| 12 |
+
develop-eggs/
|
| 13 |
+
dist/
|
| 14 |
+
downloads/
|
| 15 |
+
eggs/
|
| 16 |
+
.eggs/
|
| 17 |
+
lib/
|
| 18 |
+
lib64/
|
| 19 |
+
parts/
|
| 20 |
+
sdist/
|
| 21 |
+
var/
|
| 22 |
+
wheels/
|
| 23 |
+
share/python-wheels/
|
| 24 |
+
*.egg-info/
|
| 25 |
+
.installed.cfg
|
| 26 |
+
*.egg
|
| 27 |
+
MANIFEST
|
| 28 |
+
|
| 29 |
+
# PyInstaller
|
| 30 |
+
# Usually these files are written by a python script from a template
|
| 31 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 32 |
+
*.manifest
|
| 33 |
+
*.spec
|
| 34 |
+
|
| 35 |
+
# Installer logs
|
| 36 |
+
pip-log.txt
|
| 37 |
+
pip-delete-this-directory.txt
|
| 38 |
+
|
| 39 |
+
# Unit test / coverage reports
|
| 40 |
+
htmlcov/
|
| 41 |
+
.tox/
|
| 42 |
+
.nox/
|
| 43 |
+
.coverage
|
| 44 |
+
.coverage.*
|
| 45 |
+
.cache
|
| 46 |
+
nosetests.xml
|
| 47 |
+
coverage.xml
|
| 48 |
+
*.cover
|
| 49 |
+
*.py.cover
|
| 50 |
+
.hypothesis/
|
| 51 |
+
.pytest_cache/
|
| 52 |
+
cover/
|
| 53 |
+
|
| 54 |
+
# Translations
|
| 55 |
+
*.mo
|
| 56 |
+
*.pot
|
| 57 |
+
|
| 58 |
+
# Django stuff:
|
| 59 |
+
*.log
|
| 60 |
+
local_settings.py
|
| 61 |
+
db.sqlite3
|
| 62 |
+
db.sqlite3-journal
|
| 63 |
+
|
| 64 |
+
# Flask stuff:
|
| 65 |
+
instance/
|
| 66 |
+
.webassets-cache
|
| 67 |
+
|
| 68 |
+
# Scrapy stuff:
|
| 69 |
+
.scrapy
|
| 70 |
+
|
| 71 |
+
# Sphinx documentation
|
| 72 |
+
docs/_build/
|
| 73 |
+
|
| 74 |
+
# PyBuilder
|
| 75 |
+
.pybuilder/
|
| 76 |
+
target/
|
| 77 |
+
|
| 78 |
+
# Jupyter Notebook
|
| 79 |
+
.ipynb_checkpoints
|
| 80 |
+
|
| 81 |
+
# IPython
|
| 82 |
+
profile_default/
|
| 83 |
+
ipython_config.py
|
| 84 |
+
|
| 85 |
+
# pyenv
|
| 86 |
+
# For a library or package, you might want to ignore these files since the code is
|
| 87 |
+
# intended to run in multiple environments; otherwise, check them in:
|
| 88 |
+
# .python-version
|
| 89 |
+
|
| 90 |
+
# pipenv
|
| 91 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 92 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 93 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 94 |
+
# install all needed dependencies.
|
| 95 |
+
# Pipfile.lock
|
| 96 |
+
|
| 97 |
+
# UV
|
| 98 |
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
| 99 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 100 |
+
# commonly ignored for libraries.
|
| 101 |
+
# uv.lock
|
| 102 |
+
|
| 103 |
+
# poetry
|
| 104 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 105 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 106 |
+
# commonly ignored for libraries.
|
| 107 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
| 108 |
+
# poetry.lock
|
| 109 |
+
# poetry.toml
|
| 110 |
+
|
| 111 |
+
# pdm
|
| 112 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 113 |
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
| 114 |
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
| 115 |
+
# pdm.lock
|
| 116 |
+
# pdm.toml
|
| 117 |
+
.pdm-python
|
| 118 |
+
.pdm-build/
|
| 119 |
+
|
| 120 |
+
# pixi
|
| 121 |
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
| 122 |
+
# pixi.lock
|
| 123 |
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
| 124 |
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
| 125 |
+
.pixi
|
| 126 |
+
|
| 127 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
| 128 |
+
__pypackages__/
|
| 129 |
+
|
| 130 |
+
# Celery stuff
|
| 131 |
+
celerybeat-schedule
|
| 132 |
+
celerybeat.pid
|
| 133 |
+
|
| 134 |
+
# Redis
|
| 135 |
+
*.rdb
|
| 136 |
+
*.aof
|
| 137 |
+
*.pid
|
| 138 |
+
|
| 139 |
+
# RabbitMQ
|
| 140 |
+
mnesia/
|
| 141 |
+
rabbitmq/
|
| 142 |
+
rabbitmq-data/
|
| 143 |
+
|
| 144 |
+
# ActiveMQ
|
| 145 |
+
activemq-data/
|
| 146 |
+
|
| 147 |
+
# SageMath parsed files
|
| 148 |
+
*.sage.py
|
| 149 |
+
|
| 150 |
+
# Environments
|
| 151 |
+
.env
|
| 152 |
+
.envrc
|
| 153 |
+
.venv
|
| 154 |
+
env/
|
| 155 |
+
venv/
|
| 156 |
+
ENV/
|
| 157 |
+
env.bak/
|
| 158 |
+
venv.bak/
|
| 159 |
+
|
| 160 |
+
# Spyder project settings
|
| 161 |
+
.spyderproject
|
| 162 |
+
.spyproject
|
| 163 |
+
|
| 164 |
+
# Rope project settings
|
| 165 |
+
.ropeproject
|
| 166 |
+
|
| 167 |
+
# mkdocs documentation
|
| 168 |
+
/site
|
| 169 |
+
|
| 170 |
+
# mypy
|
| 171 |
+
.mypy_cache/
|
| 172 |
+
.dmypy.json
|
| 173 |
+
dmypy.json
|
| 174 |
+
|
| 175 |
+
# Pyre type checker
|
| 176 |
+
.pyre/
|
| 177 |
+
|
| 178 |
+
# pytype static type analyzer
|
| 179 |
+
.pytype/
|
| 180 |
+
|
| 181 |
+
# Cython debug symbols
|
| 182 |
+
cython_debug/
|
| 183 |
+
|
| 184 |
+
# PyCharm
|
| 185 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
| 186 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
| 187 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
| 188 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
| 189 |
+
# .idea/
|
| 190 |
+
|
| 191 |
+
# Abstra
|
| 192 |
+
# Abstra is an AI-powered process automation framework.
|
| 193 |
+
# Ignore directories containing user credentials, local state, and settings.
|
| 194 |
+
# Learn more at https://abstra.io/docs
|
| 195 |
+
.abstra/
|
| 196 |
+
|
| 197 |
+
# Visual Studio Code
|
| 198 |
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
| 199 |
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
| 200 |
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
| 201 |
+
# you could uncomment the following to ignore the entire vscode folder
|
| 202 |
+
.vscode/
|
| 203 |
+
|
| 204 |
+
# Ruff stuff:
|
| 205 |
+
.ruff_cache/
|
| 206 |
+
|
| 207 |
+
# PyPI configuration file
|
| 208 |
+
.pypirc
|
| 209 |
+
|
| 210 |
+
# Marimo
|
| 211 |
+
marimo/_static/
|
| 212 |
+
marimo/_lsp/
|
| 213 |
+
__marimo__/
|
| 214 |
+
|
| 215 |
+
# Streamlit
|
| 216 |
+
.streamlit/secrets.toml
|
| 217 |
+
|
| 218 |
+
# Any downloaded text files and model files I'm going to make go here, so pre-gitignoring them.
|
| 219 |
+
bin
|
| 220 |
+
|
| 221 |
+
# Covers JetBrains IDEs: IntelliJ, GoLand, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
| 222 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
| 223 |
+
|
| 224 |
+
# User-specific stuff
|
| 225 |
+
.idea/**/workspace.xml
|
| 226 |
+
.idea/**/tasks.xml
|
| 227 |
+
.idea/**/usage.statistics.xml
|
| 228 |
+
.idea/**/dictionaries
|
| 229 |
+
.idea/**/shelf
|
| 230 |
+
|
| 231 |
+
# AWS User-specific
|
| 232 |
+
.idea/**/aws.xml
|
| 233 |
+
|
| 234 |
+
# Generated files
|
| 235 |
+
.idea/**/contentModel.xml
|
| 236 |
+
|
| 237 |
+
# Sensitive or high-churn files
|
| 238 |
+
.idea/**/dataSources/
|
| 239 |
+
.idea/**/dataSources.ids
|
| 240 |
+
.idea/**/dataSources.local.xml
|
| 241 |
+
.idea/**/sqlDataSources.xml
|
| 242 |
+
.idea/**/dynamic.xml
|
| 243 |
+
.idea/**/uiDesigner.xml
|
| 244 |
+
.idea/**/dbnavigator.xml
|
| 245 |
+
|
| 246 |
+
# Gradle
|
| 247 |
+
.idea/**/gradle.xml
|
| 248 |
+
.idea/**/libraries
|
| 249 |
+
|
| 250 |
+
# Gradle and Maven with auto-import
|
| 251 |
+
# When using Gradle or Maven with auto-import, you should exclude module files,
|
| 252 |
+
# since they will be recreated, and may cause churn. Uncomment if using
|
| 253 |
+
# auto-import.
|
| 254 |
+
# .idea/artifacts
|
| 255 |
+
# .idea/compiler.xml
|
| 256 |
+
# .idea/jarRepositories.xml
|
| 257 |
+
# .idea/modules.xml
|
| 258 |
+
# .idea/*.iml
|
| 259 |
+
# .idea/modules
|
| 260 |
+
# *.iml
|
| 261 |
+
# *.ipr
|
| 262 |
+
|
| 263 |
+
# CMake
|
| 264 |
+
cmake-build-*/
|
| 265 |
+
|
| 266 |
+
# Mongo Explorer plugin
|
| 267 |
+
.idea/**/mongoSettings.xml
|
| 268 |
+
|
| 269 |
+
# File-based project format
|
| 270 |
+
*.iws
|
| 271 |
+
|
| 272 |
+
# IntelliJ
|
| 273 |
+
out/
|
| 274 |
+
|
| 275 |
+
# mpeltonen/sbt-idea plugin
|
| 276 |
+
.idea_modules/
|
| 277 |
+
|
| 278 |
+
# JIRA plugin
|
| 279 |
+
atlassian-ide-plugin.xml
|
| 280 |
+
|
| 281 |
+
# Cursive Clojure plugin
|
| 282 |
+
.idea/replstate.xml
|
| 283 |
+
|
| 284 |
+
# SonarLint plugin
|
| 285 |
+
.idea/sonarlint/
|
| 286 |
+
.idea/sonarlint.xml # see https://community.sonarsource.com/t/is-the-file-idea-idea-idea-sonarlint-xml-intended-to-be-under-source-control/121119
|
| 287 |
+
|
| 288 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
| 289 |
+
com_crashlytics_export_strings.xml
|
| 290 |
+
crashlytics.properties
|
| 291 |
+
crashlytics-build.properties
|
| 292 |
+
fabric.properties
|
| 293 |
+
|
| 294 |
+
# Editor-based HTTP Client
|
| 295 |
+
.idea/httpRequests
|
| 296 |
+
http-client.private.env.json
|
| 297 |
+
|
| 298 |
+
# Android studio 3.1+ serialized cache file
|
| 299 |
+
.idea/caches/build_file_checksums.ser
|
| 300 |
+
|
| 301 |
+
# Apifox Helper cache
|
| 302 |
+
.idea/.cache/.Apifox_Helper
|
| 303 |
+
.idea/ApifoxUploaderProjectSetting.xml
|
| 304 |
+
|
| 305 |
+
# Github Copilot persisted session migrations, see: https://github.com/microsoft/copilot-intellij-feedback/issues/712#issuecomment-3322062215
|
| 306 |
+
.idea/**/copilot.data.migration.*.xml
|
README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adria
|
| 2 |
+
|
| 3 |
+
A collection of ML experiments in NLP and language modelling.
|
| 4 |
+
|
| 5 |
+
```
|
| 6 |
+
algo/ - Training loops/algorithms
|
| 7 |
+
net/ - Model architectures
|
| 8 |
+
module/ - Reusable nn.Modules
|
| 9 |
+
tokenizer/ - Tokenizers
|
| 10 |
+
train/ - Full training scripts
|
| 11 |
+
deploy/ - Deployment scripts
|
| 12 |
+
benchmarks/ - Model benchmarks
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## Credits
|
| 16 |
+
|
| 17 |
+
Travis Geisinger ([github](https://github.com/amenyxia) / [site](https://geisinger.dev))
|
| 18 |
+
Maksimilian Lahu ([github](https://github.com/Nebulon33) / [site](https://lahu.dev))
|
| 19 |
+
|
| 20 |
+
## Citing
|
| 21 |
+
|
| 22 |
+
If this work was useful to you, consider citing:
|
| 23 |
+
|
| 24 |
+
```bibtex
|
| 25 |
+
@misc{adria,
|
| 26 |
+
author = {Travis Geisinger and Maksimilian Lahu},
|
| 27 |
+
title = {Adria: ML Experiments in NLP and Language Modelling},
|
| 28 |
+
year = {2026},
|
| 29 |
+
url = {https://github.com/Pulsar-Dynamic-Technologies/Adria}
|
| 30 |
+
}
|
| 31 |
+
```
|
algo/README.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Algo
|
| 2 |
+
|
| 3 |
+
Learning algorithms and training loops.
|
| 4 |
+
|
| 5 |
+
- `trainer.py` - Standard trainer for dense models
|
| 6 |
+
- `moe_trainer.py` - Trainer with aux loss for MoE models
|
algo/__init__py
ADDED
|
File without changes
|
algo/moe_trainer.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.amp.grad_scaler import GradScaler
|
| 6 |
+
from torch.optim import AdamW
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class MoETrainer:
|
| 10 |
+
|
| 11 |
+
def __init__(self, model, train_loader, lr=5e-4, accum_steps=8, save_dir='bin/checkpoints', aux_loss_weight=0.01):
|
| 12 |
+
|
| 13 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 14 |
+
self.model = model.to(self.device)
|
| 15 |
+
print(f">> Using device: {self.device}")
|
| 16 |
+
|
| 17 |
+
self.train_loader = train_loader
|
| 18 |
+
self.optimizer = AdamW(self.model.parameters(), lr=lr)
|
| 19 |
+
self.scaler = GradScaler()
|
| 20 |
+
self.accum_steps = accum_steps
|
| 21 |
+
self.save_dir = save_dir
|
| 22 |
+
self.aux_loss_weight = aux_loss_weight
|
| 23 |
+
self.step = 0
|
| 24 |
+
|
| 25 |
+
os.makedirs(self.save_dir, exist_ok=True)
|
| 26 |
+
|
| 27 |
+
def train(self, total_steps, log_every=100, save_every=1000, max_grad_norm: int = 1.0):
|
| 28 |
+
|
| 29 |
+
self.model.train()
|
| 30 |
+
running_loss = 0.0
|
| 31 |
+
running_aux_loss = 0.0
|
| 32 |
+
|
| 33 |
+
print(">> Starting training...")
|
| 34 |
+
|
| 35 |
+
iterator = iter(self.train_loader)
|
| 36 |
+
|
| 37 |
+
while self.step <= total_steps:
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
|
| 41 |
+
x, y = next(iterator)
|
| 42 |
+
|
| 43 |
+
except StopIteration:
|
| 44 |
+
|
| 45 |
+
iterator = iter(self.train_loader)
|
| 46 |
+
x, y = next(iterator)
|
| 47 |
+
|
| 48 |
+
x, y = x.to(self.device), y.to(self.device)
|
| 49 |
+
|
| 50 |
+
with torch.autocast(device_type='cuda', dtype=torch.float16):
|
| 51 |
+
|
| 52 |
+
logits, aux_loss = self.model(x, return_aux_loss=True)
|
| 53 |
+
B, T, C = logits.shape
|
| 54 |
+
ce_loss = nn.functional.cross_entropy(
|
| 55 |
+
logits.view(B * T, C),
|
| 56 |
+
y.view(B * T)
|
| 57 |
+
)
|
| 58 |
+
loss = (ce_loss + self.aux_loss_weight * aux_loss) / self.accum_steps
|
| 59 |
+
|
| 60 |
+
self.scaler.scale(loss).backward()
|
| 61 |
+
running_loss += ce_loss.item()
|
| 62 |
+
running_aux_loss += aux_loss.item()
|
| 63 |
+
|
| 64 |
+
if (self.step + 1) % self.accum_steps == 0:
|
| 65 |
+
|
| 66 |
+
self.scaler.unscale_(self.optimizer)
|
| 67 |
+
|
| 68 |
+
# I added that max_grad_norm parameter so we can easily experiment with it if we wanted to
|
| 69 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_grad_norm)
|
| 70 |
+
|
| 71 |
+
self.scaler.step(self.optimizer)
|
| 72 |
+
self.scaler.update()
|
| 73 |
+
self.optimizer.zero_grad()
|
| 74 |
+
|
| 75 |
+
if ((self.step // self.accum_steps) % log_every == 0) and self.step > 0:
|
| 76 |
+
print(
|
| 77 |
+
f">> Step {self.step // self.accum_steps} | Loss: {running_loss / (log_every * self.accum_steps):.4f} | Aux Loss: {running_aux_loss / (log_every * self.accum_steps):.4f}")
|
| 78 |
+
running_loss = 0.0
|
| 79 |
+
running_aux_loss = 0.0
|
| 80 |
+
|
| 81 |
+
if (self.step // self.accum_steps) % save_every == 0:
|
| 82 |
+
self.save_checkpoint(self.step // self.accum_steps)
|
| 83 |
+
|
| 84 |
+
self.step += 1
|
| 85 |
+
|
| 86 |
+
def save_checkpoint(self, step):
|
| 87 |
+
|
| 88 |
+
path = os.path.join(self.save_dir, f"checkpoint_step_{step}.pth")
|
| 89 |
+
torch.save(self.model.state_dict(), path)
|
| 90 |
+
print(f">> Saved checkpoint: {path}")
|
algo/supervised.py
ADDED
|
File without changes
|
algo/trainer.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.amp.grad_scaler import GradScaler
|
| 6 |
+
from torch.optim import AdamW
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Trainer:
|
| 10 |
+
|
| 11 |
+
def __init__(self, model, train_loader, lr=5e-4, accum_steps=8, save_dir='bin/checkpoints'):
|
| 12 |
+
|
| 13 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 14 |
+
self.model = model.to(self.device)
|
| 15 |
+
print(f">> Using device: {self.device}")
|
| 16 |
+
|
| 17 |
+
self.train_loader = train_loader
|
| 18 |
+
self.optimizer = AdamW(self.model.parameters(), lr=lr)
|
| 19 |
+
self.scaler = GradScaler()
|
| 20 |
+
self.accum_steps = accum_steps
|
| 21 |
+
self.save_dir = save_dir
|
| 22 |
+
self.step = 0
|
| 23 |
+
|
| 24 |
+
os.makedirs(self.save_dir, exist_ok=True)
|
| 25 |
+
|
| 26 |
+
def train(self, total_steps, log_every=100, save_every=1000):
|
| 27 |
+
|
| 28 |
+
self.model.train()
|
| 29 |
+
running_loss = 0.0
|
| 30 |
+
|
| 31 |
+
print(">> Starting training...")
|
| 32 |
+
|
| 33 |
+
iterator = iter(self.train_loader)
|
| 34 |
+
|
| 35 |
+
while self.step <= total_steps:
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
|
| 39 |
+
x, y = next(iterator)
|
| 40 |
+
|
| 41 |
+
except StopIteration:
|
| 42 |
+
|
| 43 |
+
iterator = iter(self.train_loader)
|
| 44 |
+
x, y = next(iterator)
|
| 45 |
+
|
| 46 |
+
x, y = x.to(self.device), y.to(self.device)
|
| 47 |
+
|
| 48 |
+
with torch.autocast(device_type='cuda', dtype=torch.float16):
|
| 49 |
+
|
| 50 |
+
logits = self.model(x)
|
| 51 |
+
B, T, C = logits.shape
|
| 52 |
+
loss = nn.functional.cross_entropy(
|
| 53 |
+
logits.view(B * T, C),
|
| 54 |
+
y.view(B * T)
|
| 55 |
+
)
|
| 56 |
+
loss = loss / self.accum_steps
|
| 57 |
+
|
| 58 |
+
self.scaler.scale(loss).backward()
|
| 59 |
+
running_loss += loss.item() * self.accum_steps
|
| 60 |
+
|
| 61 |
+
if (self.step + 1) % self.accum_steps == 0:
|
| 62 |
+
|
| 63 |
+
self.scaler.unscale_(self.optimizer)
|
| 64 |
+
|
| 65 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)
|
| 66 |
+
|
| 67 |
+
self.scaler.step(self.optimizer)
|
| 68 |
+
self.scaler.update()
|
| 69 |
+
self.optimizer.zero_grad()
|
| 70 |
+
|
| 71 |
+
if ((self.step // self.accum_steps) % log_every == 0) and self.step > 0:
|
| 72 |
+
print(
|
| 73 |
+
f">> Step {self.step // self.accum_steps} | Loss: {running_loss / (log_every * self.accum_steps):.4f}")
|
| 74 |
+
running_loss = 0.0
|
| 75 |
+
|
| 76 |
+
if (self.step // self.accum_steps) % save_every == 0:
|
| 77 |
+
self.save_checkpoint(self.step // self.accum_steps)
|
| 78 |
+
|
| 79 |
+
self.step += 1
|
| 80 |
+
|
| 81 |
+
def save_checkpoint(self, step):
|
| 82 |
+
|
| 83 |
+
path = os.path.join(self.save_dir, f"checkpoint_step_{step}.pth")
|
| 84 |
+
torch.save(self.model.state_dict(), path)
|
| 85 |
+
print(f">> Saved checkpoint: {path}")
|
benchmarks/README.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Benchmarks
|
| 2 |
+
|
| 3 |
+
This folder contains the main framework and the definition files for model and architecture benchmarks. These
|
| 4 |
+
benchmarks are meant to compare how architectures perform as SLM's to evaluate their potential when trained at
|
| 5 |
+
larger sizes.
|
| 6 |
+
|
| 7 |
+
(Note to self: In Adria folder, `python -m benchmarks.run`)
|
benchmarks/config.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
CONFIGS_PATH = Path(__file__).parent / "configs.json"
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _load_all() -> dict:
|
| 8 |
+
if CONFIGS_PATH.exists():
|
| 9 |
+
with open(CONFIGS_PATH) as f:
|
| 10 |
+
return json.load(f)
|
| 11 |
+
return {}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_config(model_name: str, n_params: int) -> dict:
|
| 15 |
+
"""
|
| 16 |
+
Load saved kwargs for (model_name, n_params).
|
| 17 |
+
Raises KeyError if no config has been saved yet for this combination.
|
| 18 |
+
config_ui.py should be run to generate these configs.
|
| 19 |
+
|
| 20 |
+
:param model_name: The name of the model to load the config for.
|
| 21 |
+
:param n_params: The parameter count to load the config for.
|
| 22 |
+
:return: The kwargs dictionary for that model config
|
| 23 |
+
"""
|
| 24 |
+
configs = _load_all()
|
| 25 |
+
model_configs = configs.get(model_name)
|
| 26 |
+
if model_configs is None:
|
| 27 |
+
raise KeyError(f"No config for {model_name}")
|
| 28 |
+
key = str(n_params)
|
| 29 |
+
if key not in model_configs:
|
| 30 |
+
raise KeyError(f"No config for {model_name} with param count {n_params}")
|
| 31 |
+
return dict(model_configs[key])
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def has_config(model_name: str, n_params: int) -> bool:
|
| 35 |
+
"""
|
| 36 |
+
Returns true if a saved config exists for (model_name, n_params).
|
| 37 |
+
|
| 38 |
+
:param model_name: The name of the model to check for the config for.
|
| 39 |
+
:param n_params: The parameter count to check for the config for.
|
| 40 |
+
:return: True if the config exists for (model_name, n_params).
|
| 41 |
+
"""
|
| 42 |
+
configs = _load_all()
|
| 43 |
+
return str(n_params) in configs.get(model_name, {})
|
benchmarks/config_ui.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI genned because it's just simple UI n' stuff.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
# Otherwise dll error
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from PyQt6.QtCore import Qt, QTimer
|
| 12 |
+
from PyQt6.QtGui import QFont
|
| 13 |
+
from PyQt6.QtWidgets import (
|
| 14 |
+
QApplication,
|
| 15 |
+
QComboBox,
|
| 16 |
+
QFormLayout,
|
| 17 |
+
QGroupBox,
|
| 18 |
+
QHBoxLayout,
|
| 19 |
+
QLabel,
|
| 20 |
+
QMainWindow,
|
| 21 |
+
QPushButton,
|
| 22 |
+
QScrollArea,
|
| 23 |
+
QSizePolicy,
|
| 24 |
+
QSpinBox,
|
| 25 |
+
QStatusBar,
|
| 26 |
+
QVBoxLayout,
|
| 27 |
+
QWidget,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
from benchmarks.registry import ModelEntry, all_models, all_tasks
|
| 31 |
+
|
| 32 |
+
from benchmarks.run import PARAM_COUNTS
|
| 33 |
+
|
| 34 |
+
# Empty statement so that jetbrains doesn't get rid of torch import
|
| 35 |
+
torch.cuda.is_available()
|
| 36 |
+
|
| 37 |
+
CONFIGS_PATH = Path(__file__).parent / "configs.json"
|
| 38 |
+
|
| 39 |
+
# Tolerance band shown in the UI (green/yellow/red)
|
| 40 |
+
TOLERANCE_GREEN = 0.05 # within 5%
|
| 41 |
+
TOLERANCE_YELLOW = 0.15 # within 15%
|
| 42 |
+
|
| 43 |
+
# Debounce delay for live recount (ms)
|
| 44 |
+
RECOUNT_DELAY = 200
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def load_configs() -> dict:
|
| 48 |
+
if CONFIGS_PATH.exists():
|
| 49 |
+
with open(CONFIGS_PATH) as f:
|
| 50 |
+
return json.load(f)
|
| 51 |
+
return {}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def save_configs(configs: dict) -> None:
|
| 55 |
+
with open(CONFIGS_PATH, "w") as f:
|
| 56 |
+
json.dump(configs, f, indent=2)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_saved(configs: dict, arch: str, n_params: int) -> dict | None:
|
| 60 |
+
return configs.get(arch, {}).get(str(n_params))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def put_saved(configs: dict, arch: str, n_params: int, kwargs: dict) -> None:
|
| 64 |
+
configs.setdefault(arch, {})[str(n_params)] = kwargs
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class FieldEditor(QWidget):
|
| 68 |
+
"""
|
| 69 |
+
A form of integer spinboxes for one arch's config kwargs.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, defaults: dict, saved: dict | None, parent=None):
|
| 73 |
+
super().__init__(parent)
|
| 74 |
+
self._fields: dict[str, QSpinBox] = {}
|
| 75 |
+
|
| 76 |
+
layout = QFormLayout(self)
|
| 77 |
+
layout.setContentsMargins(0, 0, 0, 0)
|
| 78 |
+
|
| 79 |
+
for key, default in defaults.items():
|
| 80 |
+
spin = QSpinBox()
|
| 81 |
+
spin.setMinimum(1)
|
| 82 |
+
spin.setMaximum(1_000_000)
|
| 83 |
+
spin.setValue(saved[key] if (saved and key in saved) else default)
|
| 84 |
+
spin.setGroupSeparatorShown(True)
|
| 85 |
+
self._fields[key] = spin
|
| 86 |
+
layout.addRow(key, spin)
|
| 87 |
+
|
| 88 |
+
def values(self) -> dict:
|
| 89 |
+
return {k: s.value() for k, s in self._fields.items()}
|
| 90 |
+
|
| 91 |
+
def connect_changed(self, slot) -> None:
|
| 92 |
+
for spin in self._fields.values():
|
| 93 |
+
spin.valueChanged.connect(slot)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class ConfigUI(QMainWindow):
|
| 97 |
+
def __init__(self):
|
| 98 |
+
super().__init__()
|
| 99 |
+
self.setWindowTitle("Benchmark Config Tester")
|
| 100 |
+
self.resize(700, 520)
|
| 101 |
+
|
| 102 |
+
self._configs = load_configs()
|
| 103 |
+
self._archs = all_models()
|
| 104 |
+
self._recount_timer = QTimer(self)
|
| 105 |
+
self._recount_timer.setSingleShot(True)
|
| 106 |
+
self._recount_timer.timeout.connect(self._recount)
|
| 107 |
+
|
| 108 |
+
self._build_ui()
|
| 109 |
+
self._populate_arch_list()
|
| 110 |
+
|
| 111 |
+
if self._arch_combo.count():
|
| 112 |
+
self._on_arch_changed(0)
|
| 113 |
+
|
| 114 |
+
def _build_ui(self) -> None:
|
| 115 |
+
root = QWidget()
|
| 116 |
+
self.setCentralWidget(root)
|
| 117 |
+
root_layout = QVBoxLayout(root)
|
| 118 |
+
root_layout.setContentsMargins(12, 12, 12, 12)
|
| 119 |
+
root_layout.setSpacing(10)
|
| 120 |
+
|
| 121 |
+
top = QHBoxLayout()
|
| 122 |
+
|
| 123 |
+
self._arch_combo = QComboBox()
|
| 124 |
+
self._arch_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
| 125 |
+
self._arch_combo.currentIndexChanged.connect(self._on_arch_changed)
|
| 126 |
+
top.addWidget(QLabel("Architecture:"))
|
| 127 |
+
top.addWidget(self._arch_combo)
|
| 128 |
+
|
| 129 |
+
top.addSpacing(20)
|
| 130 |
+
|
| 131 |
+
self._tier_combo = QComboBox()
|
| 132 |
+
for t in PARAM_COUNTS:
|
| 133 |
+
self._tier_combo.addItem(f"{t:,}", userData=t)
|
| 134 |
+
self._tier_combo.currentIndexChanged.connect(self._on_tier_changed)
|
| 135 |
+
top.addWidget(QLabel("Target params:"))
|
| 136 |
+
top.addWidget(self._tier_combo)
|
| 137 |
+
|
| 138 |
+
root_layout.addLayout(top)
|
| 139 |
+
|
| 140 |
+
self._range_label = QLabel("param range computed across all registered tasks")
|
| 141 |
+
self._range_label.setStyleSheet("color: grey; font-size: 10px;")
|
| 142 |
+
root_layout.addWidget(self._range_label)
|
| 143 |
+
|
| 144 |
+
self._fields_group = QGroupBox("Architecture kwargs")
|
| 145 |
+
fields_outer = QVBoxLayout(self._fields_group)
|
| 146 |
+
|
| 147 |
+
scroll = QScrollArea()
|
| 148 |
+
scroll.setWidgetResizable(True)
|
| 149 |
+
scroll.setFrameShape(scroll.Shape.NoFrame)
|
| 150 |
+
self._fields_inner = QWidget()
|
| 151 |
+
self._fields_layout = QVBoxLayout(self._fields_inner)
|
| 152 |
+
self._fields_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
|
| 153 |
+
scroll.setWidget(self._fields_inner)
|
| 154 |
+
fields_outer.addWidget(scroll)
|
| 155 |
+
|
| 156 |
+
root_layout.addWidget(self._fields_group, stretch=1)
|
| 157 |
+
|
| 158 |
+
count_group = QGroupBox("Param count")
|
| 159 |
+
count_layout = QHBoxLayout(count_group)
|
| 160 |
+
|
| 161 |
+
self._count_label = QLabel("—")
|
| 162 |
+
self._count_label.setFont(QFont("Monospace", 14, QFont.Weight.Bold))
|
| 163 |
+
self._delta_label = QLabel("")
|
| 164 |
+
self._delta_label.setFont(QFont("Monospace", 11))
|
| 165 |
+
|
| 166 |
+
count_layout.addWidget(self._count_label)
|
| 167 |
+
count_layout.addSpacing(30)
|
| 168 |
+
count_layout.addWidget(self._delta_label)
|
| 169 |
+
count_layout.addStretch()
|
| 170 |
+
|
| 171 |
+
root_layout.addWidget(count_group)
|
| 172 |
+
|
| 173 |
+
btn_row = QHBoxLayout()
|
| 174 |
+
|
| 175 |
+
self._save_btn = QPushButton("Save config for this tier")
|
| 176 |
+
self._save_btn.clicked.connect(self._save_current)
|
| 177 |
+
btn_row.addWidget(self._save_btn)
|
| 178 |
+
|
| 179 |
+
self._save_all_btn = QPushButton("Save all unsaved")
|
| 180 |
+
self._save_all_btn.setToolTip("Saves current field values for every tier that has no saved config yet")
|
| 181 |
+
self._save_all_btn.clicked.connect(self._save_all_missing)
|
| 182 |
+
btn_row.addWidget(self._save_all_btn)
|
| 183 |
+
|
| 184 |
+
btn_row.addStretch()
|
| 185 |
+
|
| 186 |
+
self._status_bar = QStatusBar()
|
| 187 |
+
root_layout.addLayout(btn_row)
|
| 188 |
+
root_layout.addWidget(self._status_bar)
|
| 189 |
+
|
| 190 |
+
self._field_editor: FieldEditor | None = None
|
| 191 |
+
|
| 192 |
+
def _populate_arch_list(self) -> None:
|
| 193 |
+
self._arch_combo.blockSignals(True)
|
| 194 |
+
self._arch_combo.clear()
|
| 195 |
+
for name, entry in self._archs.items():
|
| 196 |
+
if entry.config_tester is not None:
|
| 197 |
+
self._arch_combo.addItem(name, userData=name)
|
| 198 |
+
self._arch_combo.blockSignals(False)
|
| 199 |
+
|
| 200 |
+
def _current_arch_entry(self) -> ModelEntry | None:
|
| 201 |
+
name = self._arch_combo.currentData()
|
| 202 |
+
return self._archs.get(name) if name else None
|
| 203 |
+
|
| 204 |
+
def _current_tier(self) -> int:
|
| 205 |
+
return self._tier_combo.currentData() or PARAM_COUNTS[0]
|
| 206 |
+
|
| 207 |
+
def _on_arch_changed(self, _index: int) -> None:
|
| 208 |
+
entry = self._current_arch_entry()
|
| 209 |
+
if entry is None or entry.config_defaults is None:
|
| 210 |
+
return
|
| 211 |
+
self._rebuild_fields(entry)
|
| 212 |
+
self._recount()
|
| 213 |
+
|
| 214 |
+
def _on_tier_changed(self, _index: int) -> None:
|
| 215 |
+
entry = self._current_arch_entry()
|
| 216 |
+
if entry is None or entry.config_defaults is None:
|
| 217 |
+
return
|
| 218 |
+
|
| 219 |
+
# Load saved values for this tier if they exist
|
| 220 |
+
saved = get_saved(self._configs, entry.name, self._current_tier())
|
| 221 |
+
self._rebuild_fields(entry, saved_override=saved)
|
| 222 |
+
self._recount()
|
| 223 |
+
|
| 224 |
+
def _rebuild_fields(self, entry: ModelEntry, saved_override: dict | None = None) -> None:
|
| 225 |
+
# Remove old editor
|
| 226 |
+
if self._field_editor is not None:
|
| 227 |
+
self._fields_layout.removeWidget(self._field_editor)
|
| 228 |
+
self._field_editor.deleteLater()
|
| 229 |
+
self._field_editor = None
|
| 230 |
+
|
| 231 |
+
saved = saved_override or get_saved(self._configs, entry.name, self._current_tier())
|
| 232 |
+
editor = FieldEditor(entry.config_defaults, saved)
|
| 233 |
+
editor.connect_changed(self._schedule_recount)
|
| 234 |
+
self._fields_layout.addWidget(editor)
|
| 235 |
+
self._field_editor = editor
|
| 236 |
+
|
| 237 |
+
def _schedule_recount(self) -> None:
|
| 238 |
+
self._recount_timer.start(RECOUNT_DELAY)
|
| 239 |
+
|
| 240 |
+
def _get_task_bounds(self) -> tuple[int, int, int, int]:
|
| 241 |
+
"""(min_vocab, max_vocab, min_seq, max_seq) across all registered tasks."""
|
| 242 |
+
tasks = all_tasks()
|
| 243 |
+
if not tasks:
|
| 244 |
+
return 64, 512, 64, 512 # fallback if no tasks registered yet
|
| 245 |
+
vocabs, seqs = [], []
|
| 246 |
+
for entry in tasks.values():
|
| 247 |
+
v = entry.vocab_size(128) if callable(entry.vocab_size) else entry.vocab_size
|
| 248 |
+
vocabs.append(v)
|
| 249 |
+
seqs.append(128) # seq_len is runtime — use benchmark default as proxy
|
| 250 |
+
return min(vocabs), max(vocabs), min(seqs), max(seqs)
|
| 251 |
+
|
| 252 |
+
def _recount(self) -> None:
|
| 253 |
+
entry = self._current_arch_entry()
|
| 254 |
+
if entry is None or entry.config_tester is None or self._field_editor is None:
|
| 255 |
+
return
|
| 256 |
+
|
| 257 |
+
kwargs = self._field_editor.values()
|
| 258 |
+
target = self._current_tier()
|
| 259 |
+
min_vocab, max_vocab, min_seq, max_seq = self._get_task_bounds()
|
| 260 |
+
|
| 261 |
+
try:
|
| 262 |
+
count_lo = entry.config_tester(vocab_size=min_vocab, seq_len=min_seq, **kwargs)
|
| 263 |
+
count_hi = entry.config_tester(vocab_size=max_vocab, seq_len=max_seq, **kwargs)
|
| 264 |
+
except Exception as e:
|
| 265 |
+
self._count_label.setText("error")
|
| 266 |
+
self._delta_label.setText(str(e))
|
| 267 |
+
return
|
| 268 |
+
|
| 269 |
+
# Sort in case vocab/seq don't correlate cleanly with param count
|
| 270 |
+
count_lo, count_hi = min(count_lo, count_hi), max(count_lo, count_hi)
|
| 271 |
+
|
| 272 |
+
pct_lo = (count_lo - target) / target * 100
|
| 273 |
+
pct_hi = (count_hi - target) / target * 100
|
| 274 |
+
sign_lo = "+" if pct_lo >= 0 else ""
|
| 275 |
+
sign_hi = "+" if pct_hi >= 0 else ""
|
| 276 |
+
|
| 277 |
+
max_deviation = max(abs(pct_lo), abs(pct_hi))
|
| 278 |
+
|
| 279 |
+
self._count_label.setText(f"{count_lo:,} – {count_hi:,}")
|
| 280 |
+
self._delta_label.setText(
|
| 281 |
+
f"({sign_lo}{pct_lo:.1f}% – {sign_hi}{pct_hi:.1f}% vs target {target:,})"
|
| 282 |
+
)
|
| 283 |
+
self._range_label.setText(
|
| 284 |
+
f"range from vocab∈[{min_vocab}, {max_vocab}], seq∈[{min_seq}, {max_seq}] across {len(all_tasks())} task(s)"
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
if max_deviation <= 5.0:
|
| 288 |
+
colour = "#2ecc71"
|
| 289 |
+
elif max_deviation <= 15.0:
|
| 290 |
+
colour = "#f39c12"
|
| 291 |
+
else:
|
| 292 |
+
colour = "#e74c3c"
|
| 293 |
+
|
| 294 |
+
self._count_label.setStyleSheet(f"color: {colour};")
|
| 295 |
+
self._delta_label.setStyleSheet(f"color: {colour};")
|
| 296 |
+
|
| 297 |
+
def _save_current(self) -> None:
|
| 298 |
+
entry = self._current_arch_entry()
|
| 299 |
+
if entry is None or self._field_editor is None:
|
| 300 |
+
return
|
| 301 |
+
tier = self._current_tier()
|
| 302 |
+
kwargs = self._field_editor.values()
|
| 303 |
+
put_saved(self._configs, entry.name, tier, kwargs)
|
| 304 |
+
save_configs(self._configs)
|
| 305 |
+
self._status_bar.showMessage(
|
| 306 |
+
f"Saved {entry.name} @ {tier:,} params → {kwargs}", 5000
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
def _save_all_missing(self) -> None:
|
| 310 |
+
entry = self._current_arch_entry()
|
| 311 |
+
if entry is None or entry.config_defaults is None or self._field_editor is None:
|
| 312 |
+
return
|
| 313 |
+
|
| 314 |
+
saved_count = 0
|
| 315 |
+
|
| 316 |
+
for tier in PARAM_COUNTS:
|
| 317 |
+
if get_saved(self._configs, entry.name, tier) is not None:
|
| 318 |
+
continue
|
| 319 |
+
# Use whatever is currently in the fields for each missing tier
|
| 320 |
+
kwargs = self._field_editor.values()
|
| 321 |
+
put_saved(self._configs, entry.name, tier, kwargs)
|
| 322 |
+
saved_count += 1
|
| 323 |
+
|
| 324 |
+
if saved_count:
|
| 325 |
+
save_configs(self._configs)
|
| 326 |
+
self._status_bar.showMessage(
|
| 327 |
+
f"Saved {saved_count} missing tier(s) for {entry.name}", 5000
|
| 328 |
+
)
|
| 329 |
+
else:
|
| 330 |
+
self._status_bar.showMessage("All tiers already have saved configs.", 3000)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def main() -> None:
|
| 334 |
+
from run import MODELS_DIR, TASKS_DIR, _import_dir
|
| 335 |
+
_import_dir(MODELS_DIR)
|
| 336 |
+
_import_dir(TASKS_DIR)
|
| 337 |
+
|
| 338 |
+
app = QApplication([])
|
| 339 |
+
app.setStyle("Fusion")
|
| 340 |
+
|
| 341 |
+
window = ConfigUI()
|
| 342 |
+
window.show()
|
| 343 |
+
app.exec()
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
if __name__ == "__main__":
|
| 347 |
+
main()
|
benchmarks/configs.json
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"VanillaDecoderTransformer": {
|
| 3 |
+
"1000000": {
|
| 4 |
+
"n_layers": 5,
|
| 5 |
+
"d_model": 128,
|
| 6 |
+
"head_amount": 4,
|
| 7 |
+
"d_ffn": 512
|
| 8 |
+
},
|
| 9 |
+
"10000000": {
|
| 10 |
+
"n_layers": 12,
|
| 11 |
+
"d_model": 256,
|
| 12 |
+
"head_amount": 8,
|
| 13 |
+
"d_ffn": 1024
|
| 14 |
+
},
|
| 15 |
+
"35000000": {
|
| 16 |
+
"n_layers": 11,
|
| 17 |
+
"d_model": 512,
|
| 18 |
+
"head_amount": 8,
|
| 19 |
+
"d_ffn": 2048
|
| 20 |
+
},
|
| 21 |
+
"100000000": {
|
| 22 |
+
"n_layers": 19,
|
| 23 |
+
"d_model": 512,
|
| 24 |
+
"head_amount": 8,
|
| 25 |
+
"d_ffn": 4096
|
| 26 |
+
}
|
| 27 |
+
},
|
| 28 |
+
"RoPEVanillaDecoderTransformer": {
|
| 29 |
+
"1000000": {
|
| 30 |
+
"n_layers": 5,
|
| 31 |
+
"d_model": 128,
|
| 32 |
+
"head_amount": 4,
|
| 33 |
+
"d_ffn": 512
|
| 34 |
+
},
|
| 35 |
+
"10000000": {
|
| 36 |
+
"n_layers": 13,
|
| 37 |
+
"d_model": 256,
|
| 38 |
+
"head_amount": 8,
|
| 39 |
+
"d_ffn": 1024
|
| 40 |
+
},
|
| 41 |
+
"35000000": {
|
| 42 |
+
"n_layers": 11,
|
| 43 |
+
"d_model": 512,
|
| 44 |
+
"head_amount": 8,
|
| 45 |
+
"d_ffn": 2048
|
| 46 |
+
},
|
| 47 |
+
"100000000": {
|
| 48 |
+
"n_layers": 19,
|
| 49 |
+
"d_model": 512,
|
| 50 |
+
"head_amount": 8,
|
| 51 |
+
"d_ffn": 4096
|
| 52 |
+
}
|
| 53 |
+
},
|
| 54 |
+
"MoEVanillaDecoderTransformer": {
|
| 55 |
+
"1000000": {
|
| 56 |
+
"n_layers": 5,
|
| 57 |
+
"d_model": 128,
|
| 58 |
+
"head_amount": 8,
|
| 59 |
+
"d_ffn": 256,
|
| 60 |
+
"d_experts": 6,
|
| 61 |
+
"top_k": 2
|
| 62 |
+
},
|
| 63 |
+
"10000000": {
|
| 64 |
+
"n_layers": 8,
|
| 65 |
+
"d_model": 256,
|
| 66 |
+
"head_amount": 8,
|
| 67 |
+
"d_ffn": 1024,
|
| 68 |
+
"d_experts": 6,
|
| 69 |
+
"top_k": 2
|
| 70 |
+
},
|
| 71 |
+
"35000000": {
|
| 72 |
+
"n_layers": 11,
|
| 73 |
+
"d_model": 512,
|
| 74 |
+
"head_amount": 8,
|
| 75 |
+
"d_ffn": 1024,
|
| 76 |
+
"d_experts": 8,
|
| 77 |
+
"top_k": 2
|
| 78 |
+
},
|
| 79 |
+
"100000000": {
|
| 80 |
+
"n_layers": 11,
|
| 81 |
+
"d_model": 512,
|
| 82 |
+
"head_amount": 8,
|
| 83 |
+
"d_ffn": 4096,
|
| 84 |
+
"d_experts": 8,
|
| 85 |
+
"top_k": 2
|
| 86 |
+
}
|
| 87 |
+
},
|
| 88 |
+
"MoERoPEVanillaDecoderTransformer": {
|
| 89 |
+
"1000000": {
|
| 90 |
+
"n_layers": 5,
|
| 91 |
+
"d_model": 128,
|
| 92 |
+
"head_amount": 8,
|
| 93 |
+
"d_ffn": 256,
|
| 94 |
+
"d_experts": 6,
|
| 95 |
+
"top_k": 2
|
| 96 |
+
},
|
| 97 |
+
"10000000": {
|
| 98 |
+
"n_layers": 13,
|
| 99 |
+
"d_model": 256,
|
| 100 |
+
"head_amount": 8,
|
| 101 |
+
"d_ffn": 512,
|
| 102 |
+
"d_experts": 6,
|
| 103 |
+
"top_k": 2
|
| 104 |
+
},
|
| 105 |
+
"35000000": {
|
| 106 |
+
"n_layers": 11,
|
| 107 |
+
"d_model": 512,
|
| 108 |
+
"head_amount": 8,
|
| 109 |
+
"d_ffn": 1024,
|
| 110 |
+
"d_experts": 8,
|
| 111 |
+
"top_k": 2
|
| 112 |
+
},
|
| 113 |
+
"100000000": {
|
| 114 |
+
"n_layers": 11,
|
| 115 |
+
"d_model": 512,
|
| 116 |
+
"head_amount": 8,
|
| 117 |
+
"d_ffn": 4096,
|
| 118 |
+
"d_experts": 8,
|
| 119 |
+
"top_k": 2
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
}
|
benchmarks/models/__pycache__/moe_rope_vanilla_decoder_transformer.cpython-313.pyc
ADDED
|
Binary file (3.62 kB). View file
|
|
|
benchmarks/models/__pycache__/moe_vanilla_decoder_transformer.cpython-313.pyc
ADDED
|
Binary file (3.61 kB). View file
|
|
|
benchmarks/models/__pycache__/rope_vanilla_decoder_transformer.cpython-313.pyc
ADDED
|
Binary file (1.77 kB). View file
|
|
|
benchmarks/models/__pycache__/vanilla_decoder_transformer.cpython-313.pyc
ADDED
|
Binary file (1.76 kB). View file
|
|
|
benchmarks/models/moe_rope_vanilla_decoder_transformer.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from benchmarks.config import load_config
|
| 5 |
+
from benchmarks.registry import config_tester, model_init, train_step
|
| 6 |
+
from net import MoERoPEVanillaDecoderTransformer
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@config_tester(
|
| 10 |
+
model_name="MoERoPEVanillaDecoderTransformer",
|
| 11 |
+
n_layers=8,
|
| 12 |
+
d_model=512,
|
| 13 |
+
head_amount=8,
|
| 14 |
+
d_ffn=2048,
|
| 15 |
+
d_experts = 8,
|
| 16 |
+
top_k = 2
|
| 17 |
+
)
|
| 18 |
+
def count_params(vocab_size: int, seq_len: int, n_layers: int, d_model: int, head_amount: int, d_ffn: int, d_experts: int, top_k: int) -> float:
|
| 19 |
+
with torch.device("meta"):
|
| 20 |
+
model = MoERoPEVanillaDecoderTransformer(
|
| 21 |
+
vocab_size=vocab_size,
|
| 22 |
+
n_layers=n_layers,
|
| 23 |
+
n_ctx=seq_len,
|
| 24 |
+
d_model=d_model,
|
| 25 |
+
head_amount=head_amount,
|
| 26 |
+
d_ffn=d_ffn,
|
| 27 |
+
d_experts=d_experts,
|
| 28 |
+
top_k=top_k
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
total = sum(p.numel() for p in model.parameters())
|
| 32 |
+
|
| 33 |
+
# Literally just total - (expert Param * top k)
|
| 34 |
+
params_per_expert = sum(p.numel() for p in model.blocks[0].ffn.experts[0].parameters())
|
| 35 |
+
unused_per_layer = (d_experts - top_k) * params_per_expert
|
| 36 |
+
|
| 37 |
+
return total - (n_layers * unused_per_layer)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@model_init(
|
| 41 |
+
model_name="MoERoPEVanillaDecoderTransformer"
|
| 42 |
+
)
|
| 43 |
+
def make_model(n_params: int, vocab_size: int, seq_len: int) -> nn.Module:
|
| 44 |
+
cfg = load_config("MoERoPEVanillaDecoderTransformer", n_params)
|
| 45 |
+
return MoERoPEVanillaDecoderTransformer(
|
| 46 |
+
vocab_size=vocab_size,
|
| 47 |
+
n_ctx=seq_len,
|
| 48 |
+
**cfg
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@train_step(model_name="MoERoPEVanillaDecoderTransformer")
|
| 53 |
+
def moe_train_step(model, optimizer, input_ids, target, loss_mask):
|
| 54 |
+
optimizer.zero_grad()
|
| 55 |
+
logits, aux_loss = model(input_ids, return_aux_loss=True)
|
| 56 |
+
B, T, C = logits.shape
|
| 57 |
+
loss = nn.functional.cross_entropy(
|
| 58 |
+
logits.view(B * T, C),
|
| 59 |
+
target.view(B * T),
|
| 60 |
+
reduction="none",
|
| 61 |
+
)
|
| 62 |
+
loss = (loss * loss_mask.view(B * T).float()).sum() / loss_mask.sum().clamp(min=1)
|
| 63 |
+
(loss + aux_loss).backward()
|
| 64 |
+
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 65 |
+
optimizer.step()
|
| 66 |
+
return loss.item()
|
benchmarks/models/moe_vanilla_decoder_transformer.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from benchmarks.config import load_config
|
| 5 |
+
from benchmarks.registry import config_tester, model_init, train_step
|
| 6 |
+
from net import MoEVanillaDecoderTransformer
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@config_tester(
|
| 10 |
+
model_name="MoEVanillaDecoderTransformer",
|
| 11 |
+
n_layers=8,
|
| 12 |
+
d_model=512,
|
| 13 |
+
head_amount=8,
|
| 14 |
+
d_ffn=2048,
|
| 15 |
+
d_experts = 8,
|
| 16 |
+
top_k = 2
|
| 17 |
+
)
|
| 18 |
+
def count_params(vocab_size: int, seq_len: int, n_layers: int, d_model: int, head_amount: int, d_ffn: int, d_experts: int, top_k: int) -> float:
|
| 19 |
+
with torch.device("meta"):
|
| 20 |
+
model = MoEVanillaDecoderTransformer(
|
| 21 |
+
vocab_size=vocab_size,
|
| 22 |
+
n_layers=n_layers,
|
| 23 |
+
n_ctx=seq_len,
|
| 24 |
+
d_model=d_model,
|
| 25 |
+
head_amount=head_amount,
|
| 26 |
+
d_ffn=d_ffn,
|
| 27 |
+
d_experts=d_experts,
|
| 28 |
+
top_k=top_k
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
total = sum(p.numel() for p in model.parameters())
|
| 32 |
+
|
| 33 |
+
# Literally just total - (expert Param * top k)
|
| 34 |
+
params_per_expert = sum(p.numel() for p in model.blocks[0].ffn.experts[0].parameters())
|
| 35 |
+
unused_per_layer = (d_experts - top_k) * params_per_expert
|
| 36 |
+
|
| 37 |
+
return total - (n_layers * unused_per_layer)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@model_init(
|
| 41 |
+
model_name="MoEVanillaDecoderTransformer"
|
| 42 |
+
)
|
| 43 |
+
def make_model(n_params: int, vocab_size: int, seq_len: int) -> nn.Module:
|
| 44 |
+
cfg = load_config("MoEVanillaDecoderTransformer", n_params)
|
| 45 |
+
return MoEVanillaDecoderTransformer(
|
| 46 |
+
vocab_size=vocab_size,
|
| 47 |
+
n_ctx=seq_len,
|
| 48 |
+
**cfg
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@train_step(model_name="MoEVanillaDecoderTransformer")
|
| 53 |
+
def moe_train_step(model, optimizer, input_ids, target, loss_mask):
|
| 54 |
+
optimizer.zero_grad()
|
| 55 |
+
logits, aux_loss = model(input_ids, return_aux_loss=True)
|
| 56 |
+
B, T, C = logits.shape
|
| 57 |
+
loss = nn.functional.cross_entropy(
|
| 58 |
+
logits.view(B * T, C),
|
| 59 |
+
target.view(B * T),
|
| 60 |
+
reduction="none",
|
| 61 |
+
)
|
| 62 |
+
loss = (loss * loss_mask.view(B * T).float()).sum() / loss_mask.sum().clamp(min=1)
|
| 63 |
+
(loss + aux_loss).backward()
|
| 64 |
+
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 65 |
+
optimizer.step()
|
| 66 |
+
return loss.item()
|
benchmarks/models/rope_vanilla_decoder_transformer.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from benchmarks.config import load_config
|
| 5 |
+
from benchmarks.registry import config_tester, model_init
|
| 6 |
+
from net import RoPEVanillaDecoderTransformer
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@config_tester(
|
| 10 |
+
model_name="RoPEVanillaDecoderTransformer",
|
| 11 |
+
n_layers=8,
|
| 12 |
+
d_model=512,
|
| 13 |
+
head_amount=8,
|
| 14 |
+
d_ffn=2048,
|
| 15 |
+
)
|
| 16 |
+
def count_params(vocab_size: int, seq_len: int, n_layers: int, d_model: int, head_amount: int, d_ffn: int):
|
| 17 |
+
with torch.device("meta"):
|
| 18 |
+
model = RoPEVanillaDecoderTransformer(
|
| 19 |
+
vocab_size=vocab_size,
|
| 20 |
+
n_layers=n_layers,
|
| 21 |
+
n_ctx=seq_len,
|
| 22 |
+
d_model=d_model,
|
| 23 |
+
head_amount=head_amount,
|
| 24 |
+
d_ffn=d_ffn
|
| 25 |
+
)
|
| 26 |
+
return sum(p.numel() for p in model.parameters())
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@model_init(
|
| 30 |
+
model_name="RoPEVanillaDecoderTransformer"
|
| 31 |
+
)
|
| 32 |
+
def make_model(n_params: int, vocab_size: int, seq_len: int) -> nn.Module:
|
| 33 |
+
cfg = load_config("RoPEVanillaDecoderTransformer", n_params)
|
| 34 |
+
return RoPEVanillaDecoderTransformer(
|
| 35 |
+
vocab_size=vocab_size,
|
| 36 |
+
n_ctx=seq_len,
|
| 37 |
+
**cfg
|
| 38 |
+
)
|
benchmarks/models/vanilla_decoder_transformer.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from benchmarks.config import load_config
|
| 5 |
+
from benchmarks.registry import config_tester, model_init
|
| 6 |
+
from net import VanillaDecoderTransformer
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@config_tester(
|
| 10 |
+
model_name="VanillaDecoderTransformer",
|
| 11 |
+
n_layers=8,
|
| 12 |
+
d_model=512,
|
| 13 |
+
head_amount=8,
|
| 14 |
+
d_ffn=2048,
|
| 15 |
+
)
|
| 16 |
+
def count_params(vocab_size: int, seq_len: int, n_layers: int, d_model: int, head_amount: int, d_ffn: int):
|
| 17 |
+
with torch.device("meta"):
|
| 18 |
+
model = VanillaDecoderTransformer(
|
| 19 |
+
vocab_size=vocab_size,
|
| 20 |
+
n_layers=n_layers,
|
| 21 |
+
n_ctx=seq_len,
|
| 22 |
+
d_model=d_model,
|
| 23 |
+
head_amount=head_amount,
|
| 24 |
+
d_ffn=d_ffn
|
| 25 |
+
)
|
| 26 |
+
return sum(p.numel() for p in model.parameters())
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@model_init(
|
| 30 |
+
model_name="VanillaDecoderTransformer"
|
| 31 |
+
)
|
| 32 |
+
def make_model(n_params: int, vocab_size: int, seq_len: int) -> nn.Module:
|
| 33 |
+
cfg = load_config("VanillaDecoderTransformer", n_params)
|
| 34 |
+
return VanillaDecoderTransformer(
|
| 35 |
+
vocab_size=vocab_size,
|
| 36 |
+
n_ctx=seq_len,
|
| 37 |
+
**cfg
|
| 38 |
+
)
|
benchmarks/registry.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
from typing import Callable, Generator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
Batch = tuple[torch.Tensor, torch.Tensor, torch.Tensor]
|
| 8 |
+
BatchGenerator = Generator[Batch, None, None]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclasses.dataclass
|
| 12 |
+
class ModelEntry:
|
| 13 |
+
name: str
|
| 14 |
+
make_model: Callable[[int, int, int], nn.Module]
|
| 15 |
+
make_optimizer: Callable[[nn.Module], torch.optim.Optimizer] | None = None
|
| 16 |
+
train_step: Callable[
|
| 17 |
+
[nn.Module, torch.optim.Optimizer, torch.Tensor, torch.Tensor, torch.Tensor], float] | None = None
|
| 18 |
+
config_tester: Callable | None = None
|
| 19 |
+
config_defaults: dict | None = None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_model_registry: dict[str, ModelEntry] = {}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _get_or_create_arch(name: str) -> ModelEntry:
|
| 26 |
+
if name not in _model_registry:
|
| 27 |
+
# noinspection PyTypeChecker
|
| 28 |
+
_model_registry[name] = ModelEntry(name=name, make_model=None)
|
| 29 |
+
return _model_registry[name]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def model_init(model_name: str):
|
| 33 |
+
"""
|
| 34 |
+
Register a model factory function.
|
| 35 |
+
The decorated function must have signature:
|
| 36 |
+
(n_params: int, vocab_size: int, seq_len: int) -> nn.Module
|
| 37 |
+
|
| 38 |
+
:param model_name: The name of the model to register.
|
| 39 |
+
:return: None
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def decorator(func: Callable) -> Callable:
|
| 43 |
+
entry = _get_or_create_arch(model_name)
|
| 44 |
+
entry.make_model = func
|
| 45 |
+
return func
|
| 46 |
+
|
| 47 |
+
return decorator
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def optimizer(model_name: str):
|
| 51 |
+
"""
|
| 52 |
+
Optionally override the default optimizer for a model.
|
| 53 |
+
If not provided, the default optimizer (AdamW) will be used.
|
| 54 |
+
The decorated function must have signature:
|
| 55 |
+
(model: nn.Module) -> torch.optim.Optimizer
|
| 56 |
+
|
| 57 |
+
:param model_name: The name of the model to register the optimizer for.
|
| 58 |
+
:return: None
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def decorator(func: Callable) -> Callable:
|
| 62 |
+
entry = _get_or_create_arch(model_name)
|
| 63 |
+
entry.make_optimizer = func
|
| 64 |
+
return func
|
| 65 |
+
|
| 66 |
+
return decorator
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def train_step(model_name: str):
|
| 70 |
+
"""
|
| 71 |
+
Optionally override the default training step for a model.
|
| 72 |
+
The decorated function must have signature:
|
| 73 |
+
(model, optimizer, input_ids, target_ids, loss_mask) -> float
|
| 74 |
+
|
| 75 |
+
:param model_name: The name of the model to register the training step for.
|
| 76 |
+
:return: None
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def decorator(func: Callable) -> Callable:
|
| 80 |
+
entry = _get_or_create_arch(model_name)
|
| 81 |
+
entry.train_step = func
|
| 82 |
+
return func
|
| 83 |
+
|
| 84 |
+
return decorator
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def config_tester(model_name: str, **defaults):
|
| 88 |
+
"""
|
| 89 |
+
Register a param counter for a simple config UI.
|
| 90 |
+
Decorator kwargs are the architecture-specific fields and their defaults.
|
| 91 |
+
The decorated function must have signature:
|
| 92 |
+
(vocab_size: int, seq_len: int, **kwargs) -> int
|
| 93 |
+
where **kwargs matches the decorator kwargs.
|
| 94 |
+
|
| 95 |
+
:param model_name: The name of the model to register the param counter for.
|
| 96 |
+
:param defaults: Params with default values for all params that the config UI should vary.
|
| 97 |
+
:return: None
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def decorator(func: Callable) -> Callable:
|
| 101 |
+
entry = _get_or_create_arch(model_name)
|
| 102 |
+
entry.config_tester = func
|
| 103 |
+
entry.config_defaults = defaults
|
| 104 |
+
return func
|
| 105 |
+
|
| 106 |
+
return decorator
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dataclasses.dataclass
|
| 110 |
+
class TaskEntry:
|
| 111 |
+
name: str
|
| 112 |
+
vocab_size: int | Callable[[int], int]
|
| 113 |
+
batch_generator: Callable[[int, int, int | None], BatchGenerator]
|
| 114 |
+
seq_len: int
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
_task_registry: dict[str, TaskEntry] = {}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def task(name: str, vocab_size: int | Callable[[int], int], seq_len: int = 64):
|
| 121 |
+
"""
|
| 122 |
+
Register a task generator.
|
| 123 |
+
|
| 124 |
+
The decorated function must have signature:
|
| 125 |
+
(seq_len: int, batch_size: int, seed: int | None = None) -> Generator[Batch, None, None]
|
| 126 |
+
|
| 127 |
+
where Batch = (input_ids, target_ids, loss_mask), all (B, T) tensors.
|
| 128 |
+
input_ids and target_ids are torch.long; loss_mask is torch.bool.
|
| 129 |
+
|
| 130 |
+
vocab_size may be a plain int or a callable (seq_len) -> int for tasks
|
| 131 |
+
whose vocab grows with sequence length.
|
| 132 |
+
|
| 133 |
+
:param name: The name of the task to register.
|
| 134 |
+
:param vocab_size: The plain int or callable (seq_len) -> int for tasks.
|
| 135 |
+
:param seq_len: The sequence length to use for this task.
|
| 136 |
+
:return: None
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
def decorator(func: Callable) -> Callable:
|
| 140 |
+
_task_registry[name] = TaskEntry(
|
| 141 |
+
name=name,
|
| 142 |
+
vocab_size=vocab_size,
|
| 143 |
+
batch_generator=func,
|
| 144 |
+
seq_len=seq_len,
|
| 145 |
+
)
|
| 146 |
+
return func
|
| 147 |
+
|
| 148 |
+
return decorator
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def get_model(model_name: str) -> ModelEntry:
|
| 152 |
+
if model_name not in _model_registry:
|
| 153 |
+
raise KeyError(f"No arch registered under name '{model_name}'.")
|
| 154 |
+
if _model_registry[model_name].make_model is None:
|
| 155 |
+
raise KeyError(f"Model '{model_name}' has no @model_init function.")
|
| 156 |
+
return _model_registry[model_name]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def get_task(task_name: str) -> TaskEntry:
|
| 160 |
+
if task_name not in _task_registry:
|
| 161 |
+
raise KeyError(f"No task registered under name '{task_name}'.")
|
| 162 |
+
return _task_registry[task_name]
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def all_models() -> dict[str, ModelEntry]:
|
| 166 |
+
return dict(_model_registry)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def all_tasks() -> dict[str, TaskEntry]:
|
| 170 |
+
return dict(_task_registry)
|
benchmarks/results.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
RESULTS_DIR = Path(__file__).parent / "results"
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclasses.dataclass
|
| 9 |
+
class StepRecord:
|
| 10 |
+
"""
|
| 11 |
+
A dataclass to help logging and graphing by holding one step of results
|
| 12 |
+
"""
|
| 13 |
+
step: int
|
| 14 |
+
tokens: int
|
| 15 |
+
loss: float
|
| 16 |
+
accuracy: float
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclasses.dataclass
|
| 20 |
+
class TaskResult:
|
| 21 |
+
model_name: str
|
| 22 |
+
task_name: str
|
| 23 |
+
n_params: int
|
| 24 |
+
seq_len: int
|
| 25 |
+
batch_size: int
|
| 26 |
+
total_steps: int
|
| 27 |
+
total_tokens: int
|
| 28 |
+
curve: list[StepRecord]
|
| 29 |
+
final_loss: float
|
| 30 |
+
final_accuracy: float
|
| 31 |
+
tokens_to_90pct: int | None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def result_path(model_name: str, task_name: str, n_params: int) -> Path:
|
| 35 |
+
return RESULTS_DIR / model_name / f"{task_name}_{n_params}.json"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def result_exists(model_name: str, task_name: str, n_params: int) -> bool:
|
| 39 |
+
return result_path(model_name, task_name, n_params).exists()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def save_result(result: TaskResult, params: int):
|
| 43 |
+
path = result_path(result.model_name, result.task_name, params)
|
| 44 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 45 |
+
with open(path, "w") as f:
|
| 46 |
+
json.dump(dataclasses.asdict(result), f, indent=4)
|
| 47 |
+
f.close()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def load_result(model_name: str, task_name: str, n_params: int) -> TaskResult:
|
| 51 |
+
path = result_path(model_name, task_name, n_params)
|
| 52 |
+
with open(path) as f:
|
| 53 |
+
result = json.load(f)
|
| 54 |
+
f.close()
|
| 55 |
+
result["curve"] = [StepRecord(**r) for r in result["curve"]]
|
| 56 |
+
return TaskResult(**result)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def load_all_results() -> list[TaskResult]:
|
| 60 |
+
results = []
|
| 61 |
+
for path in RESULTS_DIR.rglob("*.json"):
|
| 62 |
+
# noinspection PyBroadException
|
| 63 |
+
try:
|
| 64 |
+
model_name = path.parent.name
|
| 65 |
+
filename_parts = path.stem.rsplit("_", 1)
|
| 66 |
+
task_name, n_params = filename_parts[0], int(filename_parts[1])
|
| 67 |
+
results.append(load_result(model_name, task_name, n_params))
|
| 68 |
+
except Exception:
|
| 69 |
+
pass
|
| 70 |
+
return results
|
benchmarks/run.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from importlib import util
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
|
| 11 |
+
from benchmarks.registry import ModelEntry, TaskEntry, all_models, all_tasks
|
| 12 |
+
from benchmarks.results import TaskResult, StepRecord, result_exists, save_result
|
| 13 |
+
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
MLFLOW_TRACKING_URI = os.getenv("MLFLOW_TRACKING_URI")
|
| 17 |
+
MLFLOW_ENABLED = MLFLOW_TRACKING_URI is not None
|
| 18 |
+
|
| 19 |
+
if MLFLOW_ENABLED:
|
| 20 |
+
try:
|
| 21 |
+
import mlflow
|
| 22 |
+
mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)
|
| 23 |
+
except ImportError:
|
| 24 |
+
MLFLOW_ENABLED = False
|
| 25 |
+
print("Warning: mlflow not installed. Disabling MLflow tracking.")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
MODELS_DIR = Path(__file__).parent / "models"
|
| 29 |
+
TASKS_DIR = Path(__file__).parent / "tasks"
|
| 30 |
+
|
| 31 |
+
DEFAULT_PARAM_COUNTS = [1_000_000, 10_000_000, 35_000_000, 100_000_000]
|
| 32 |
+
|
| 33 |
+
DEFAULT_MAX_STEPS = 10_000
|
| 34 |
+
DEFAULT_BATCH_SIZE = 64
|
| 35 |
+
LOG_EVERY = 10
|
| 36 |
+
EVAL_EVERY = 100
|
| 37 |
+
TIME_LIMIT_SECONDS = 60 * 60
|
| 38 |
+
DEFAULT_SEED = 42
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _import_dir(directory: Path) -> None:
|
| 42 |
+
"""
|
| 43 |
+
Import every .py file in the given directory.
|
| 44 |
+
Useful for auto model and task registration.
|
| 45 |
+
|
| 46 |
+
:param directory: The directory to import from.
|
| 47 |
+
:return: None
|
| 48 |
+
"""
|
| 49 |
+
for path in sorted(directory.glob("*.py")):
|
| 50 |
+
if path.name.startswith("_"):
|
| 51 |
+
continue
|
| 52 |
+
spec = util.spec_from_file_location(path.stem, path)
|
| 53 |
+
mod = util.module_from_spec(spec)
|
| 54 |
+
spec.loader.exec_module(mod)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _default_optimizer(model: nn.Module) -> torch.optim.Optimizer:
|
| 58 |
+
return torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=1e-2, betas=(0.9, 0.95))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _default_train_step(
|
| 62 |
+
model: nn.Module,
|
| 63 |
+
optimizer: torch.optim.Optimizer,
|
| 64 |
+
input_ids: torch.Tensor,
|
| 65 |
+
target: torch.Tensor,
|
| 66 |
+
loss_mask: torch.Tensor,
|
| 67 |
+
) -> float:
|
| 68 |
+
optimizer.zero_grad()
|
| 69 |
+
logits = model(input_ids)
|
| 70 |
+
B, T, C = logits.shape
|
| 71 |
+
loss = nn.functional.cross_entropy(
|
| 72 |
+
logits.view(B * T, C),
|
| 73 |
+
target.view(B * T),
|
| 74 |
+
reduction="none",
|
| 75 |
+
)
|
| 76 |
+
loss = (loss * loss_mask.view(B * T).float()).sum() / loss_mask.sum().clamp(min=1)
|
| 77 |
+
loss.backward()
|
| 78 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 79 |
+
optimizer.step()
|
| 80 |
+
return loss.item()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _tokens_to_threshold(curve: list[StepRecord], threshold: float = 0.90) -> int | None:
|
| 84 |
+
for r in curve:
|
| 85 |
+
if r.accuracy >= threshold:
|
| 86 |
+
return r.tokens
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def run_task(
|
| 91 |
+
model_entry: ModelEntry,
|
| 92 |
+
task_entry: TaskEntry,
|
| 93 |
+
n_params: int,
|
| 94 |
+
batch_size: int,
|
| 95 |
+
max_steps: int,
|
| 96 |
+
device: str = "cuda",
|
| 97 |
+
seed: int = DEFAULT_SEED,
|
| 98 |
+
) -> TaskResult:
|
| 99 |
+
seq_len = task_entry.seq_len
|
| 100 |
+
|
| 101 |
+
vocab_size = (
|
| 102 |
+
task_entry.vocab_size(seq_len)
|
| 103 |
+
if callable(task_entry.vocab_size)
|
| 104 |
+
else task_entry.vocab_size
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
torch.manual_seed(seed)
|
| 108 |
+
if device == 'cuda':
|
| 109 |
+
torch.cuda.manual_seed(seed)
|
| 110 |
+
model = model_entry.make_model(n_params, vocab_size, seq_len).to(device)
|
| 111 |
+
|
| 112 |
+
make_opt = model_entry.make_optimizer or _default_optimizer
|
| 113 |
+
opt = make_opt(model)
|
| 114 |
+
|
| 115 |
+
train_step = model_entry.train_step or _default_train_step
|
| 116 |
+
|
| 117 |
+
train_gen = task_entry.batch_generator(seq_len, batch_size, seed + 1)
|
| 118 |
+
test_gen = task_entry.batch_generator(seq_len, batch_size, seed + 2)
|
| 119 |
+
|
| 120 |
+
test_batches = [(e_input.to(device), e_target.to(device), e_mask.to(device))
|
| 121 |
+
for e_input, e_target, e_mask in [next(test_gen) for _ in range(10)]]
|
| 122 |
+
|
| 123 |
+
actual_params = sum(p.numel() for p in model.parameters())
|
| 124 |
+
|
| 125 |
+
mlflow_run = None
|
| 126 |
+
if MLFLOW_ENABLED:
|
| 127 |
+
try:
|
| 128 |
+
mlflow.set_experiment(task_entry.name)
|
| 129 |
+
mlflow_run = mlflow.start_run(run_name=f"{model_entry.name}-{n_params}")
|
| 130 |
+
mlflow.set_tags({
|
| 131 |
+
"model": model_entry.name,
|
| 132 |
+
"task": task_entry.name,
|
| 133 |
+
})
|
| 134 |
+
mlflow.log_params({
|
| 135 |
+
"actual_params": actual_params,
|
| 136 |
+
"target_params": n_params,
|
| 137 |
+
"seq_len": seq_len,
|
| 138 |
+
"batch_size": batch_size,
|
| 139 |
+
"vocab_size": vocab_size,
|
| 140 |
+
"max_steps": max_steps,
|
| 141 |
+
"device": device,
|
| 142 |
+
})
|
| 143 |
+
for param_group in opt.param_groups:
|
| 144 |
+
mlflow.log_param("lr", param_group.get("lr", "unknown"))
|
| 145 |
+
mlflow.log_param("weight_decay", param_group.get("weight_decay", "unknown"))
|
| 146 |
+
break
|
| 147 |
+
except Exception as e:
|
| 148 |
+
print(f"Warning: Failed to connect to MLflow server: {e}")
|
| 149 |
+
mlflow_run = None
|
| 150 |
+
|
| 151 |
+
verbose = not MLFLOW_ENABLED or mlflow_run is None
|
| 152 |
+
print(f"Model: {model_entry.name}\n\tTask: {task_entry.name}\n\tParams: {actual_params}\n\tVocabSize: {vocab_size}")
|
| 153 |
+
|
| 154 |
+
curve: list[StepRecord] = []
|
| 155 |
+
total_tokens = 0
|
| 156 |
+
t_start = time.time()
|
| 157 |
+
last_log_time = time.time()
|
| 158 |
+
|
| 159 |
+
model.train()
|
| 160 |
+
current_eval_acc = 0.0
|
| 161 |
+
exit_reason = "max_steps"
|
| 162 |
+
|
| 163 |
+
for step in range(1, max_steps + 1):
|
| 164 |
+
if time.time() - t_start > TIME_LIMIT_SECONDS:
|
| 165 |
+
exit_reason = "time_limit"
|
| 166 |
+
print(f"Time limit reached at step {step}.")
|
| 167 |
+
break
|
| 168 |
+
|
| 169 |
+
input_ids, target_ids, loss_mask = next(train_gen)
|
| 170 |
+
input_ids = input_ids.to(device)
|
| 171 |
+
target_ids = target_ids.to(device)
|
| 172 |
+
loss_mask = loss_mask.to(device)
|
| 173 |
+
|
| 174 |
+
loss = train_step(model, opt, input_ids, target_ids, loss_mask)
|
| 175 |
+
total_tokens += batch_size * seq_len
|
| 176 |
+
|
| 177 |
+
if step % EVAL_EVERY == 0:
|
| 178 |
+
|
| 179 |
+
model.eval()
|
| 180 |
+
|
| 181 |
+
total_eval_correct = 0
|
| 182 |
+
total_eval_masked = 0
|
| 183 |
+
perfect_batches = 0
|
| 184 |
+
with torch.no_grad():
|
| 185 |
+
for e_input, e_target, e_mask in test_batches:
|
| 186 |
+
|
| 187 |
+
logits = model(e_input)
|
| 188 |
+
predictions = logits.argmax(dim=-1)
|
| 189 |
+
correct = (predictions == e_target) & e_mask.bool()
|
| 190 |
+
|
| 191 |
+
batch_correct = correct.sum().item()
|
| 192 |
+
batch_total = e_mask.sum().clamp(min=1).item()
|
| 193 |
+
|
| 194 |
+
total_eval_correct += batch_correct
|
| 195 |
+
total_eval_masked += batch_total
|
| 196 |
+
|
| 197 |
+
if batch_correct == batch_total:
|
| 198 |
+
perfect_batches += 1
|
| 199 |
+
|
| 200 |
+
model.train()
|
| 201 |
+
|
| 202 |
+
current_eval_acc = total_eval_correct / max(total_eval_masked, 1)
|
| 203 |
+
elapsed = time.time() - t_start
|
| 204 |
+
steps_per_sec = LOG_EVERY / (time.time() - last_log_time)
|
| 205 |
+
last_log_time = time.time()
|
| 206 |
+
|
| 207 |
+
if mlflow_run:
|
| 208 |
+
mlflow.log_metrics({
|
| 209 |
+
"eval_accuracy": current_eval_acc,
|
| 210 |
+
"train_loss": loss,
|
| 211 |
+
"steps_per_sec": steps_per_sec,
|
| 212 |
+
}, step=step)
|
| 213 |
+
|
| 214 |
+
if verbose:
|
| 215 |
+
print(f"\n\t[EVAL] Step {step}: {elapsed:.2f}s | Eval Accuracy: {current_eval_acc * 100:.2f}%")
|
| 216 |
+
|
| 217 |
+
if perfect_batches == 10:
|
| 218 |
+
exit_reason = "early_stop"
|
| 219 |
+
print(f"\tPassed 10/10 evaluation batches with 100% accuracy at step {step}. Exiting early.")
|
| 220 |
+
curve.append(StepRecord(step=step, tokens=total_tokens, loss=loss, accuracy=current_eval_acc))
|
| 221 |
+
break
|
| 222 |
+
|
| 223 |
+
if step % LOG_EVERY == 0:
|
| 224 |
+
record = StepRecord(
|
| 225 |
+
step=step,
|
| 226 |
+
tokens=total_tokens,
|
| 227 |
+
loss=loss,
|
| 228 |
+
accuracy=current_eval_acc,
|
| 229 |
+
)
|
| 230 |
+
curve.append(record)
|
| 231 |
+
|
| 232 |
+
if mlflow_run and step % EVAL_EVERY != 0:
|
| 233 |
+
mlflow.log_metric("train_loss", loss, step=step)
|
| 234 |
+
|
| 235 |
+
if verbose and step % EVAL_EVERY != 0:
|
| 236 |
+
print(f"\tStep {step} | Train Loss: {loss:.4e}")
|
| 237 |
+
|
| 238 |
+
final = curve[-1] if curve else StepRecord(0, 0, float("nan"), 0.0)
|
| 239 |
+
elapsed_total = time.time() - t_start
|
| 240 |
+
|
| 241 |
+
if mlflow_run:
|
| 242 |
+
converged = final.accuracy >= 0.9
|
| 243 |
+
mlflow.set_tags({
|
| 244 |
+
"exit_reason": exit_reason,
|
| 245 |
+
"converged": str(converged).lower(),
|
| 246 |
+
})
|
| 247 |
+
mlflow.log_metrics({
|
| 248 |
+
"final_loss": final.loss,
|
| 249 |
+
"final_accuracy": final.accuracy,
|
| 250 |
+
"total_steps": final.step,
|
| 251 |
+
"total_tokens": total_tokens,
|
| 252 |
+
"total_elapsed_sec": elapsed_total,
|
| 253 |
+
"tokens_to_90pct": _tokens_to_threshold(curve) or 0,
|
| 254 |
+
})
|
| 255 |
+
mlflow.end_run()
|
| 256 |
+
|
| 257 |
+
if verbose:
|
| 258 |
+
print(f"\tFinal Loss: {final.loss:.4e}")
|
| 259 |
+
print(f"\tFinal Accuracy: {final.accuracy:.2%}")
|
| 260 |
+
|
| 261 |
+
return TaskResult(
|
| 262 |
+
model_name=model_entry.name,
|
| 263 |
+
task_name=task_entry.name,
|
| 264 |
+
n_params=actual_params,
|
| 265 |
+
seq_len=seq_len,
|
| 266 |
+
batch_size=batch_size,
|
| 267 |
+
total_steps=final.step,
|
| 268 |
+
total_tokens=total_tokens,
|
| 269 |
+
curve=curve,
|
| 270 |
+
final_loss=final.loss,
|
| 271 |
+
final_accuracy=final.accuracy,
|
| 272 |
+
tokens_to_90pct=_tokens_to_threshold(curve),
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def main() -> None:
|
| 277 |
+
parser = argparse.ArgumentParser(description="Run model benchmarks on tasks")
|
| 278 |
+
parser.add_argument("--seed", type=int, default=DEFAULT_SEED, help=f"Random seed (default: {DEFAULT_SEED})")
|
| 279 |
+
parser.add_argument("--batch-size", type=int, default=DEFAULT_BATCH_SIZE, help=f"Batch size (default: {DEFAULT_BATCH_SIZE})")
|
| 280 |
+
parser.add_argument("--max-steps", type=int, default=DEFAULT_MAX_STEPS, help=f"Maximum training steps (default: {DEFAULT_MAX_STEPS})")
|
| 281 |
+
parser.add_argument("--device", type=str, default="cuda", help="Device to use (default: cuda)")
|
| 282 |
+
parser.add_argument("--model", type=str, default=None, help="Filter to specific model name")
|
| 283 |
+
parser.add_argument("--task", type=str, default=None, help="Filter to specific task name")
|
| 284 |
+
parser.add_argument("--params", type=int, nargs="+", default=None, help="Filter to specific param counts")
|
| 285 |
+
parser.add_argument("--rerun", action="store_true", help="Rerun tests even if results exist")
|
| 286 |
+
args = parser.parse_args()
|
| 287 |
+
|
| 288 |
+
_import_dir(MODELS_DIR)
|
| 289 |
+
_import_dir(TASKS_DIR)
|
| 290 |
+
|
| 291 |
+
models = all_models()
|
| 292 |
+
tasks = all_tasks()
|
| 293 |
+
|
| 294 |
+
if args.model:
|
| 295 |
+
models = {k: v for k, v in models.items() if args.model.lower() in k.lower()}
|
| 296 |
+
if args.task:
|
| 297 |
+
tasks = {k: v for k, v in tasks.items() if args.task.lower() in k.lower()}
|
| 298 |
+
|
| 299 |
+
param_counts = args.params if args.params else DEFAULT_PARAM_COUNTS
|
| 300 |
+
|
| 301 |
+
pending = []
|
| 302 |
+
skipped = 0
|
| 303 |
+
for n_params in param_counts:
|
| 304 |
+
for task_name, task_entry in tasks.items():
|
| 305 |
+
for model_name, model_entry in models.items():
|
| 306 |
+
if not args.rerun and result_exists(model_name, task_name, n_params):
|
| 307 |
+
skipped += 1
|
| 308 |
+
else:
|
| 309 |
+
pending.append((model_entry, task_entry, n_params))
|
| 310 |
+
|
| 311 |
+
total = len(pending) + skipped
|
| 312 |
+
print(f"\nFound {len(models)} models, {len(tasks)} tasks and {len(param_counts)} param sizes.")
|
| 313 |
+
print(f"{total} combinations total, {skipped} skipped, {len(pending)} pending.\n")
|
| 314 |
+
|
| 315 |
+
for i, (model_entry, task_entry, n_params) in enumerate(pending):
|
| 316 |
+
print(f"\n{i}/{len(pending)}")
|
| 317 |
+
result = run_task(
|
| 318 |
+
model_entry,
|
| 319 |
+
task_entry,
|
| 320 |
+
n_params,
|
| 321 |
+
args.batch_size,
|
| 322 |
+
args.max_steps,
|
| 323 |
+
device=args.device,
|
| 324 |
+
seed=args.seed,
|
| 325 |
+
)
|
| 326 |
+
save_result(result, n_params)
|
| 327 |
+
print(f"Saved results for {model_entry.name}, task {task_entry.name}.")
|
| 328 |
+
|
| 329 |
+
print("\nDone.")
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
if __name__ == "__main__":
|
| 333 |
+
main()
|
benchmarks/tasks/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from benchmarks.tasks import short_range
|
| 2 |
+
from benchmarks.tasks import long_range
|
| 3 |
+
from benchmarks.tasks import state
|
| 4 |
+
from benchmarks.tasks import counting
|
| 5 |
+
from benchmarks.tasks import rule_extraction
|
| 6 |
+
from benchmarks.tasks import composition
|
| 7 |
+
from benchmarks.tasks import aggregation
|
| 8 |
+
from benchmarks.tasks import hierarchical
|
benchmarks/tasks/__pycache__/aggregation.cpython-313.pyc
ADDED
|
Binary file (7.26 kB). View file
|
|
|
benchmarks/tasks/__pycache__/composition.cpython-313.pyc
ADDED
|
Binary file (8.34 kB). View file
|
|
|
benchmarks/tasks/__pycache__/counting.cpython-313.pyc
ADDED
|
Binary file (7.05 kB). View file
|
|
|
benchmarks/tasks/__pycache__/hierarchical.cpython-313.pyc
ADDED
|
Binary file (9.6 kB). View file
|
|
|
benchmarks/tasks/__pycache__/long_range.cpython-313.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
benchmarks/tasks/__pycache__/rule_extraction.cpython-313.pyc
ADDED
|
Binary file (7.28 kB). View file
|
|
|
benchmarks/tasks/__pycache__/short_range.cpython-313.pyc
ADDED
|
Binary file (7.36 kB). View file
|
|
|
benchmarks/tasks/__pycache__/state.cpython-313.pyc
ADDED
|
Binary file (7.18 kB). View file
|
|
|
benchmarks/tasks/aggregation.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from typing import Generator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from benchmarks.registry import Batch, BatchGenerator, task
|
| 7 |
+
|
| 8 |
+
PAD = 0
|
| 9 |
+
SEP = 1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _sort_impl(seq_len: int, batch_size: int, min_len: int, max_len: int, seed: int | None = None) -> BatchGenerator:
|
| 13 |
+
rng = random.Random(seed)
|
| 14 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 15 |
+
|
| 16 |
+
while True:
|
| 17 |
+
while len(buffer_input) < batch_size:
|
| 18 |
+
vocab_size = rng.randint(6, 16)
|
| 19 |
+
data_tokens = list(range(2, 2 + vocab_size))
|
| 20 |
+
|
| 21 |
+
max_seq_len = (seq_len - 1) // 2
|
| 22 |
+
seq_len_actual = rng.randint(min_len, min(max_len, max_seq_len))
|
| 23 |
+
|
| 24 |
+
sequence = [rng.choice(data_tokens) for _ in range(seq_len_actual)]
|
| 25 |
+
sorted_seq = sorted(sequence)
|
| 26 |
+
prefix = sequence
|
| 27 |
+
|
| 28 |
+
for i in range(len(sorted_seq)):
|
| 29 |
+
input_seq = prefix + [SEP] + sorted_seq[:i]
|
| 30 |
+
target_seq = prefix[1:] + [SEP] + sorted_seq[:i+1]
|
| 31 |
+
|
| 32 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 33 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 34 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 35 |
+
|
| 36 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 37 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 38 |
+
|
| 39 |
+
ans_pos = len(input_seq) - 1
|
| 40 |
+
if ans_pos < seq_len:
|
| 41 |
+
loss_mask[ans_pos] = True
|
| 42 |
+
buffer_input.append(input_ids)
|
| 43 |
+
buffer_target.append(target_ids)
|
| 44 |
+
buffer_mask.append(loss_mask)
|
| 45 |
+
|
| 46 |
+
yield (
|
| 47 |
+
torch.stack(buffer_input[:batch_size]),
|
| 48 |
+
torch.stack(buffer_target[:batch_size]),
|
| 49 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 50 |
+
)
|
| 51 |
+
buffer_input = buffer_input[batch_size:]
|
| 52 |
+
buffer_target = buffer_target[batch_size:]
|
| 53 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@task("sort_64", vocab_size=18, seq_len=64)
|
| 57 |
+
def sort_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 58 |
+
return _sort_impl(seq_len, batch_size, min_len=4, max_len=12, seed=seed)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@task("sort_128", vocab_size=18, seq_len=128)
|
| 62 |
+
def sort_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 63 |
+
return _sort_impl(seq_len, batch_size, min_len=4, max_len=24, seed=seed)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _run_length_encode_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 67 |
+
rng = random.Random(seed)
|
| 68 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 69 |
+
|
| 70 |
+
while True:
|
| 71 |
+
while len(buffer_input) < batch_size:
|
| 72 |
+
n_runs = rng.randint(2, 8)
|
| 73 |
+
symbol_vocab_size = rng.randint(4, 10)
|
| 74 |
+
max_run_len = 6
|
| 75 |
+
|
| 76 |
+
sym_start = 2
|
| 77 |
+
sym_end = sym_start + 10
|
| 78 |
+
symbols = list(range(sym_start, sym_start + symbol_vocab_size))
|
| 79 |
+
|
| 80 |
+
count_start = sym_end
|
| 81 |
+
|
| 82 |
+
runs, sequence = [], []
|
| 83 |
+
for _ in range(n_runs):
|
| 84 |
+
sym = rng.choice(symbols)
|
| 85 |
+
run_len = rng.randint(1, max_run_len)
|
| 86 |
+
runs.append((sym, run_len))
|
| 87 |
+
sequence.extend([sym] * run_len)
|
| 88 |
+
|
| 89 |
+
answer = []
|
| 90 |
+
for sym, run_len in runs:
|
| 91 |
+
answer.extend([sym, count_start + run_len - 1])
|
| 92 |
+
|
| 93 |
+
max_total = len(sequence) + 1 + len(answer)
|
| 94 |
+
if max_total > seq_len:
|
| 95 |
+
scale = seq_len / max_total
|
| 96 |
+
n_runs = max(1, int(n_runs * scale))
|
| 97 |
+
runs, sequence, answer = [], [], []
|
| 98 |
+
for _ in range(n_runs):
|
| 99 |
+
sym = rng.choice(symbols)
|
| 100 |
+
run_len = rng.randint(1, max_run_len)
|
| 101 |
+
runs.append((sym, run_len))
|
| 102 |
+
sequence.extend([sym] * run_len)
|
| 103 |
+
answer.extend([sym, count_start + run_len - 1])
|
| 104 |
+
|
| 105 |
+
prefix = sequence
|
| 106 |
+
|
| 107 |
+
for i in range(len(answer)):
|
| 108 |
+
input_seq = prefix + [SEP] + answer[:i]
|
| 109 |
+
target_seq = prefix[1:] + [SEP] + answer[:i+1]
|
| 110 |
+
|
| 111 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 112 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 113 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 114 |
+
|
| 115 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 116 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 117 |
+
|
| 118 |
+
ans_pos = len(input_seq) - 1
|
| 119 |
+
if ans_pos < seq_len:
|
| 120 |
+
loss_mask[ans_pos] = True
|
| 121 |
+
buffer_input.append(input_ids)
|
| 122 |
+
buffer_target.append(target_ids)
|
| 123 |
+
buffer_mask.append(loss_mask)
|
| 124 |
+
|
| 125 |
+
yield (
|
| 126 |
+
torch.stack(buffer_input[:batch_size]),
|
| 127 |
+
torch.stack(buffer_target[:batch_size]),
|
| 128 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 129 |
+
)
|
| 130 |
+
buffer_input = buffer_input[batch_size:]
|
| 131 |
+
buffer_target = buffer_target[batch_size:]
|
| 132 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@task("run_length_encode_64", vocab_size=20, seq_len=64)
|
| 136 |
+
def run_length_encode_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 137 |
+
return _run_length_encode_impl(seq_len, batch_size, seed)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@task("run_length_encode_128", vocab_size=20, seq_len=128)
|
| 141 |
+
def run_length_encode_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 142 |
+
return _run_length_encode_impl(seq_len, batch_size, seed)
|
benchmarks/tasks/composition.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from typing import Generator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from benchmarks.registry import Batch, BatchGenerator, task
|
| 7 |
+
|
| 8 |
+
PAD = 0
|
| 9 |
+
SEP = 1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _two_hop_retrieval_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 13 |
+
rng = random.Random(seed)
|
| 14 |
+
while True:
|
| 15 |
+
batch_input = []
|
| 16 |
+
batch_target = []
|
| 17 |
+
batch_mask = []
|
| 18 |
+
|
| 19 |
+
for _ in range(batch_size):
|
| 20 |
+
n_chains = rng.randint(2, 5)
|
| 21 |
+
|
| 22 |
+
A_start = 2
|
| 23 |
+
A_end = A_start + n_chains
|
| 24 |
+
B_start = A_end
|
| 25 |
+
B_end = B_start + n_chains
|
| 26 |
+
C_start = B_end
|
| 27 |
+
C_end = C_start + n_chains
|
| 28 |
+
FILLER_start = C_end
|
| 29 |
+
FILLER_end = FILLER_start + n_chains
|
| 30 |
+
|
| 31 |
+
a_keys = list(range(A_start, A_end))
|
| 32 |
+
b_keys = list(range(B_start, B_end))
|
| 33 |
+
c_vals = list(range(C_start, C_end))
|
| 34 |
+
filler_tokens = list(range(FILLER_start, FILLER_end))
|
| 35 |
+
|
| 36 |
+
chains = list(zip(a_keys, b_keys, c_vals))
|
| 37 |
+
rng.shuffle(chains)
|
| 38 |
+
|
| 39 |
+
a_to_b = {a: b for a, b, c in chains}
|
| 40 |
+
b_to_c = {b: c for a, b, c in chains}
|
| 41 |
+
|
| 42 |
+
max_filler = 3
|
| 43 |
+
prefix = []
|
| 44 |
+
|
| 45 |
+
for a, b, c in chains:
|
| 46 |
+
prefix.append(a)
|
| 47 |
+
prefix.append(b)
|
| 48 |
+
if rng.random() < 0.3:
|
| 49 |
+
for _ in range(rng.randint(0, max_filler)):
|
| 50 |
+
prefix.append(rng.choice(filler_tokens))
|
| 51 |
+
|
| 52 |
+
for a, b, c in chains:
|
| 53 |
+
prefix.append(b)
|
| 54 |
+
prefix.append(c)
|
| 55 |
+
if rng.random() < 0.3:
|
| 56 |
+
for _ in range(rng.randint(0, max_filler)):
|
| 57 |
+
prefix.append(rng.choice(filler_tokens))
|
| 58 |
+
|
| 59 |
+
query_a = rng.choice(a_keys)
|
| 60 |
+
answer_c = b_to_c[a_to_b[query_a]]
|
| 61 |
+
|
| 62 |
+
input_seq = prefix + [SEP, query_a]
|
| 63 |
+
target_seq = prefix[1:] + [SEP, query_a, answer_c]
|
| 64 |
+
|
| 65 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 66 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 67 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 68 |
+
|
| 69 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 70 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 71 |
+
|
| 72 |
+
ans_pos = len(input_seq) - 1
|
| 73 |
+
if ans_pos < seq_len:
|
| 74 |
+
loss_mask[ans_pos] = True
|
| 75 |
+
|
| 76 |
+
batch_input.append(input_ids)
|
| 77 |
+
batch_target.append(target_ids)
|
| 78 |
+
batch_mask.append(loss_mask)
|
| 79 |
+
|
| 80 |
+
yield (
|
| 81 |
+
torch.stack(batch_input),
|
| 82 |
+
torch.stack(batch_target),
|
| 83 |
+
torch.stack(batch_mask),
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@task("two_hop_retrieval_64", vocab_size=25, seq_len=64)
|
| 88 |
+
def two_hop_retrieval_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 89 |
+
return _two_hop_retrieval_impl(seq_len, batch_size, seed)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@task("two_hop_retrieval_128", vocab_size=25, seq_len=128)
|
| 93 |
+
def two_hop_retrieval_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 94 |
+
return _two_hop_retrieval_impl(seq_len, batch_size, seed)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _binary_addition_impl(seq_len: int, batch_size: int, min_bits: int, max_bits: int, seed: int | None = None) -> BatchGenerator:
|
| 98 |
+
rng = random.Random(seed)
|
| 99 |
+
BIT_0 = 2
|
| 100 |
+
BIT_1 = 3
|
| 101 |
+
|
| 102 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 103 |
+
|
| 104 |
+
while True:
|
| 105 |
+
while len(buffer_input) < batch_size:
|
| 106 |
+
n_bits = rng.randint(min_bits, max_bits)
|
| 107 |
+
|
| 108 |
+
a = rng.randint(0, 2**n_bits - 1)
|
| 109 |
+
b = rng.randint(0, 2**n_bits - 1)
|
| 110 |
+
s = a + b
|
| 111 |
+
|
| 112 |
+
def to_bits(n, length):
|
| 113 |
+
bits = []
|
| 114 |
+
for i in range(length - 1, -1, -1):
|
| 115 |
+
bits.append(BIT_1 if (n >> i) & 1 else BIT_0)
|
| 116 |
+
return bits
|
| 117 |
+
|
| 118 |
+
a_bits = to_bits(a, n_bits)
|
| 119 |
+
b_bits = to_bits(b, n_bits)
|
| 120 |
+
s_bit_len = max(n_bits, s.bit_length())
|
| 121 |
+
s_bits = to_bits(s, s_bit_len)
|
| 122 |
+
|
| 123 |
+
max_total = 2 * n_bits + 2 + len(s_bits)
|
| 124 |
+
if max_total > seq_len:
|
| 125 |
+
n_bits = (seq_len - 3) // 3
|
| 126 |
+
if n_bits < min_bits:
|
| 127 |
+
n_bits = min_bits
|
| 128 |
+
a = rng.randint(0, 2**n_bits - 1)
|
| 129 |
+
b = rng.randint(0, 2**n_bits - 1)
|
| 130 |
+
s = a + b
|
| 131 |
+
a_bits = to_bits(a, n_bits)
|
| 132 |
+
b_bits = to_bits(b, n_bits)
|
| 133 |
+
s_bit_len = max(n_bits, s.bit_length())
|
| 134 |
+
s_bits = to_bits(s, s_bit_len)
|
| 135 |
+
|
| 136 |
+
prefix = a_bits + [SEP] + b_bits + [SEP]
|
| 137 |
+
|
| 138 |
+
for i in range(len(s_bits)):
|
| 139 |
+
input_seq = prefix + s_bits[:i]
|
| 140 |
+
target_seq = prefix[1:] + s_bits[:i+1]
|
| 141 |
+
|
| 142 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 143 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 144 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 145 |
+
|
| 146 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 147 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 148 |
+
|
| 149 |
+
ans_pos = len(input_seq) - 1
|
| 150 |
+
if ans_pos < seq_len:
|
| 151 |
+
loss_mask[ans_pos] = True
|
| 152 |
+
|
| 153 |
+
buffer_input.append(input_ids)
|
| 154 |
+
buffer_target.append(target_ids)
|
| 155 |
+
buffer_mask.append(loss_mask)
|
| 156 |
+
|
| 157 |
+
yield (
|
| 158 |
+
torch.stack(buffer_input[:batch_size]),
|
| 159 |
+
torch.stack(buffer_target[:batch_size]),
|
| 160 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 161 |
+
)
|
| 162 |
+
buffer_input = buffer_input[batch_size:]
|
| 163 |
+
buffer_target = buffer_target[batch_size:]
|
| 164 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@task("binary_addition_64", vocab_size=4, seq_len=64)
|
| 168 |
+
def binary_addition_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 169 |
+
return _binary_addition_impl(seq_len, batch_size, min_bits=3, max_bits=8, seed=seed)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@task("binary_addition_128", vocab_size=4, seq_len=128)
|
| 173 |
+
def binary_addition_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 174 |
+
return _binary_addition_impl(seq_len, batch_size, min_bits=4, max_bits=16, seed=seed)
|
benchmarks/tasks/counting.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from collections import Counter
|
| 3 |
+
from typing import Generator
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from benchmarks.registry import Batch, BatchGenerator, task
|
| 8 |
+
|
| 9 |
+
PAD = 0
|
| 10 |
+
SEP = 1
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _token_histogram_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 14 |
+
rng = random.Random(seed)
|
| 15 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 16 |
+
|
| 17 |
+
while True:
|
| 18 |
+
while len(buffer_input) < batch_size:
|
| 19 |
+
vocab_size = rng.randint(4, 8)
|
| 20 |
+
data_start = 2
|
| 21 |
+
data_end = data_start + vocab_size
|
| 22 |
+
data_tokens = list(range(data_start, data_end))
|
| 23 |
+
|
| 24 |
+
count_start = data_end
|
| 25 |
+
max_seq_len = seq_len - vocab_size - 1
|
| 26 |
+
seq_len_actual = rng.randint(8, min(30, max_seq_len))
|
| 27 |
+
|
| 28 |
+
sequence = [rng.choice(data_tokens) for _ in range(seq_len_actual)]
|
| 29 |
+
counts = Counter(sequence)
|
| 30 |
+
|
| 31 |
+
answer = []
|
| 32 |
+
for token in range(data_start, data_end):
|
| 33 |
+
answer.append(count_start + counts.get(token, 0))
|
| 34 |
+
|
| 35 |
+
prefix = sequence
|
| 36 |
+
|
| 37 |
+
for i in range(len(answer)):
|
| 38 |
+
input_seq = prefix + [SEP] + answer[:i]
|
| 39 |
+
target_seq = prefix[1:] + [SEP] + answer[:i+1]
|
| 40 |
+
|
| 41 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 42 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 43 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 44 |
+
|
| 45 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 46 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 47 |
+
|
| 48 |
+
ans_pos = len(input_seq) - 1
|
| 49 |
+
if ans_pos < seq_len:
|
| 50 |
+
loss_mask[ans_pos] = True
|
| 51 |
+
buffer_input.append(input_ids)
|
| 52 |
+
buffer_target.append(target_ids)
|
| 53 |
+
buffer_mask.append(loss_mask)
|
| 54 |
+
|
| 55 |
+
yield (
|
| 56 |
+
torch.stack(buffer_input[:batch_size]),
|
| 57 |
+
torch.stack(buffer_target[:batch_size]),
|
| 58 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 59 |
+
)
|
| 60 |
+
buffer_input = buffer_input[batch_size:]
|
| 61 |
+
buffer_target = buffer_target[batch_size:]
|
| 62 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@task("token_histogram_64", vocab_size=50, seq_len=64)
|
| 66 |
+
def token_histogram_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 67 |
+
return _token_histogram_impl(seq_len, batch_size, seed)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@task("token_histogram_128", vocab_size=50, seq_len=128)
|
| 71 |
+
def token_histogram_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 72 |
+
return _token_histogram_impl(seq_len, batch_size, seed)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _majority_token_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 76 |
+
rng = random.Random(seed)
|
| 77 |
+
while True:
|
| 78 |
+
batch_input = []
|
| 79 |
+
batch_target = []
|
| 80 |
+
batch_mask = []
|
| 81 |
+
|
| 82 |
+
for _ in range(batch_size):
|
| 83 |
+
vocab_size = rng.randint(4, 8)
|
| 84 |
+
data_tokens = list(range(2, 2 + vocab_size))
|
| 85 |
+
|
| 86 |
+
seq_len_actual = rng.randint(8, 30)
|
| 87 |
+
|
| 88 |
+
for _ in range(100):
|
| 89 |
+
sequence = [rng.choice(data_tokens) for _ in range(seq_len_actual)]
|
| 90 |
+
counts = Counter(sequence)
|
| 91 |
+
most_common = counts.most_common(2)
|
| 92 |
+
if len(most_common) == 1 or most_common[0][1] > most_common[1][1]:
|
| 93 |
+
break
|
| 94 |
+
else:
|
| 95 |
+
majority_token = rng.choice(data_tokens)
|
| 96 |
+
sequence = [majority_token] * (seq_len_actual // 2 + 1)
|
| 97 |
+
sequence += [rng.choice([t for t in data_tokens if t != majority_token])
|
| 98 |
+
for _ in range(seq_len_actual - len(sequence))]
|
| 99 |
+
counts = Counter(sequence)
|
| 100 |
+
most_common = counts.most_common(2)
|
| 101 |
+
|
| 102 |
+
majority = most_common[0][0]
|
| 103 |
+
|
| 104 |
+
input_seq = sequence + [SEP]
|
| 105 |
+
target_seq = sequence[1:] + [SEP, majority]
|
| 106 |
+
|
| 107 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 108 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 109 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 110 |
+
|
| 111 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 112 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 113 |
+
|
| 114 |
+
ans_pos = len(input_seq) - 1
|
| 115 |
+
if ans_pos < seq_len:
|
| 116 |
+
loss_mask[ans_pos] = True
|
| 117 |
+
|
| 118 |
+
batch_input.append(input_ids)
|
| 119 |
+
batch_target.append(target_ids)
|
| 120 |
+
batch_mask.append(loss_mask)
|
| 121 |
+
|
| 122 |
+
yield (
|
| 123 |
+
torch.stack(batch_input),
|
| 124 |
+
torch.stack(batch_target),
|
| 125 |
+
torch.stack(batch_mask),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@task("majority_token_64", vocab_size=10, seq_len=64)
|
| 130 |
+
def majority_token_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 131 |
+
return _majority_token_impl(seq_len, batch_size, seed)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@task("majority_token_128", vocab_size=10, seq_len=128)
|
| 135 |
+
def majority_token_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 136 |
+
return _majority_token_impl(seq_len, batch_size, seed)
|
benchmarks/tasks/hierarchical.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from typing import Generator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from benchmarks.registry import Batch, BatchGenerator, task
|
| 7 |
+
|
| 8 |
+
PAD = 0
|
| 9 |
+
SEP = 1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _dyck1_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 13 |
+
rng = random.Random(seed)
|
| 14 |
+
while True:
|
| 15 |
+
batch_input = []
|
| 16 |
+
batch_target = []
|
| 17 |
+
batch_mask = []
|
| 18 |
+
|
| 19 |
+
OPEN = 2
|
| 20 |
+
CLOSE = 3
|
| 21 |
+
|
| 22 |
+
max_depth = rng.randint(2, 5)
|
| 23 |
+
|
| 24 |
+
for _ in range(batch_size):
|
| 25 |
+
sequence = []
|
| 26 |
+
depth = 0
|
| 27 |
+
|
| 28 |
+
while len(sequence) <= seq_len:
|
| 29 |
+
if depth == 0:
|
| 30 |
+
sequence.append(OPEN)
|
| 31 |
+
depth += 1
|
| 32 |
+
elif depth >= max_depth:
|
| 33 |
+
sequence.append(CLOSE)
|
| 34 |
+
depth -= 1
|
| 35 |
+
else:
|
| 36 |
+
if rng.random() < 0.5:
|
| 37 |
+
sequence.append(OPEN)
|
| 38 |
+
depth += 1
|
| 39 |
+
else:
|
| 40 |
+
sequence.append(CLOSE)
|
| 41 |
+
depth -= 1
|
| 42 |
+
|
| 43 |
+
if len(sequence) < 2:
|
| 44 |
+
sequence = [OPEN, CLOSE]
|
| 45 |
+
|
| 46 |
+
input_seq = sequence[:-1]
|
| 47 |
+
target_seq = sequence[1:]
|
| 48 |
+
|
| 49 |
+
input_ids = torch.tensor(input_seq, dtype=torch.long)[:seq_len]
|
| 50 |
+
target_ids = torch.tensor(target_seq, dtype=torch.long)[:seq_len]
|
| 51 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 52 |
+
|
| 53 |
+
for i, tok in enumerate(target_seq[:seq_len]):
|
| 54 |
+
if tok == CLOSE:
|
| 55 |
+
loss_mask[i] = True
|
| 56 |
+
|
| 57 |
+
batch_input.append(input_ids)
|
| 58 |
+
batch_target.append(target_ids)
|
| 59 |
+
batch_mask.append(loss_mask)
|
| 60 |
+
|
| 61 |
+
yield (
|
| 62 |
+
torch.stack(batch_input),
|
| 63 |
+
torch.stack(batch_target),
|
| 64 |
+
torch.stack(batch_mask),
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@task("dyck1_64", vocab_size=4, seq_len=64)
|
| 69 |
+
def dyck1_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 70 |
+
return _dyck1_impl(seq_len, batch_size, seed)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _dyck2_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 74 |
+
rng = random.Random(seed)
|
| 75 |
+
while True:
|
| 76 |
+
batch_input = []
|
| 77 |
+
batch_target = []
|
| 78 |
+
batch_mask = []
|
| 79 |
+
|
| 80 |
+
OPEN_A = 2
|
| 81 |
+
CLOSE_A = 3
|
| 82 |
+
OPEN_B = 4
|
| 83 |
+
CLOSE_B = 5
|
| 84 |
+
|
| 85 |
+
max_depth = rng.randint(2, 4)
|
| 86 |
+
|
| 87 |
+
for _ in range(batch_size):
|
| 88 |
+
sequence = []
|
| 89 |
+
stack = []
|
| 90 |
+
|
| 91 |
+
while len(sequence) <= seq_len:
|
| 92 |
+
if len(stack) == 0:
|
| 93 |
+
bracket_type = rng.choice(['A', 'B'])
|
| 94 |
+
if bracket_type == 'A':
|
| 95 |
+
sequence.append(OPEN_A)
|
| 96 |
+
stack.append('A')
|
| 97 |
+
else:
|
| 98 |
+
sequence.append(OPEN_B)
|
| 99 |
+
stack.append('B')
|
| 100 |
+
elif len(stack) >= max_depth:
|
| 101 |
+
bracket_type = stack.pop()
|
| 102 |
+
if bracket_type == 'A':
|
| 103 |
+
sequence.append(CLOSE_A)
|
| 104 |
+
else:
|
| 105 |
+
sequence.append(CLOSE_B)
|
| 106 |
+
else:
|
| 107 |
+
if rng.random() < 0.5:
|
| 108 |
+
bracket_type = rng.choice(['A', 'B'])
|
| 109 |
+
if bracket_type == 'A':
|
| 110 |
+
sequence.append(OPEN_A)
|
| 111 |
+
stack.append('A')
|
| 112 |
+
else:
|
| 113 |
+
sequence.append(OPEN_B)
|
| 114 |
+
stack.append('B')
|
| 115 |
+
else:
|
| 116 |
+
bracket_type = stack.pop()
|
| 117 |
+
if bracket_type == 'A':
|
| 118 |
+
sequence.append(CLOSE_A)
|
| 119 |
+
else:
|
| 120 |
+
sequence.append(CLOSE_B)
|
| 121 |
+
|
| 122 |
+
if len(sequence) < 2:
|
| 123 |
+
sequence = [OPEN_A, CLOSE_A]
|
| 124 |
+
|
| 125 |
+
input_seq = sequence[:-1]
|
| 126 |
+
target_seq = sequence[1:]
|
| 127 |
+
|
| 128 |
+
input_ids = torch.tensor(input_seq, dtype=torch.long)[:seq_len]
|
| 129 |
+
target_ids = torch.tensor(target_seq, dtype=torch.long)[:seq_len]
|
| 130 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 131 |
+
|
| 132 |
+
for i, tok in enumerate(target_seq[:seq_len]):
|
| 133 |
+
if tok in [CLOSE_A, CLOSE_B]:
|
| 134 |
+
loss_mask[i] = True
|
| 135 |
+
|
| 136 |
+
batch_input.append(input_ids)
|
| 137 |
+
batch_target.append(target_ids)
|
| 138 |
+
batch_mask.append(loss_mask)
|
| 139 |
+
|
| 140 |
+
yield (
|
| 141 |
+
torch.stack(batch_input),
|
| 142 |
+
torch.stack(batch_target),
|
| 143 |
+
torch.stack(batch_mask),
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@task("dyck2_64", vocab_size=6, seq_len=64)
|
| 148 |
+
def dyck2_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 149 |
+
return _dyck2_impl(seq_len, batch_size, seed)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _prefix_arithmetic_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 153 |
+
rng = random.Random(seed)
|
| 154 |
+
|
| 155 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 156 |
+
|
| 157 |
+
OP_ADD = 2
|
| 158 |
+
OP_SUB = 3
|
| 159 |
+
OP_MUL = 4
|
| 160 |
+
INT_START = 5
|
| 161 |
+
INT_END = INT_START + 10
|
| 162 |
+
DIGIT_START = INT_END
|
| 163 |
+
SIGN_NEG = DIGIT_START + 10
|
| 164 |
+
|
| 165 |
+
while True:
|
| 166 |
+
while len(buffer_input) < batch_size:
|
| 167 |
+
max_depth = rng.randint(1, 3)
|
| 168 |
+
|
| 169 |
+
def generate_expr(depth: int):
|
| 170 |
+
if depth == 0:
|
| 171 |
+
val = rng.randint(0, 9)
|
| 172 |
+
return [INT_START + val], val
|
| 173 |
+
op = rng.choice([OP_ADD, OP_SUB, OP_MUL])
|
| 174 |
+
left_tokens, left_val = generate_expr(depth - 1)
|
| 175 |
+
right_tokens, right_val = generate_expr(depth - 1)
|
| 176 |
+
if op == OP_ADD:
|
| 177 |
+
result = left_val + right_val
|
| 178 |
+
elif op == OP_SUB:
|
| 179 |
+
result = left_val - right_val
|
| 180 |
+
else:
|
| 181 |
+
result = left_val * right_val
|
| 182 |
+
result = max(-999, min(999, result))
|
| 183 |
+
return [op] + left_tokens + right_tokens, result
|
| 184 |
+
|
| 185 |
+
expr_tokens, result = generate_expr(max_depth)
|
| 186 |
+
|
| 187 |
+
def encode_result(n: int):
|
| 188 |
+
if n < 0:
|
| 189 |
+
digits = [SIGN_NEG]
|
| 190 |
+
n = -n
|
| 191 |
+
else:
|
| 192 |
+
digits = []
|
| 193 |
+
n_str = str(n)
|
| 194 |
+
for d in n_str:
|
| 195 |
+
digits.append(DIGIT_START + int(d))
|
| 196 |
+
return digits
|
| 197 |
+
|
| 198 |
+
result_tokens = encode_result(result)
|
| 199 |
+
|
| 200 |
+
if len(expr_tokens) + 1 + len(result_tokens) > seq_len:
|
| 201 |
+
expr_tokens, result = generate_expr(1)
|
| 202 |
+
result_tokens = encode_result(result)
|
| 203 |
+
|
| 204 |
+
prefix = expr_tokens
|
| 205 |
+
|
| 206 |
+
for i in range(len(result_tokens)):
|
| 207 |
+
input_seq = prefix + [SEP] + result_tokens[:i]
|
| 208 |
+
target_seq = prefix[1:] + [SEP] + result_tokens[:i+1]
|
| 209 |
+
|
| 210 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 211 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 212 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 213 |
+
|
| 214 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 215 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 216 |
+
|
| 217 |
+
ans_pos = len(input_seq) - 1
|
| 218 |
+
if ans_pos < seq_len:
|
| 219 |
+
loss_mask[ans_pos] = True
|
| 220 |
+
|
| 221 |
+
buffer_input.append(input_ids)
|
| 222 |
+
buffer_target.append(target_ids)
|
| 223 |
+
buffer_mask.append(loss_mask)
|
| 224 |
+
|
| 225 |
+
yield (
|
| 226 |
+
torch.stack(buffer_input[:batch_size]),
|
| 227 |
+
torch.stack(buffer_target[:batch_size]),
|
| 228 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 229 |
+
)
|
| 230 |
+
buffer_input = buffer_input[batch_size:]
|
| 231 |
+
buffer_target = buffer_target[batch_size:]
|
| 232 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@task("prefix_arithmetic_64", vocab_size=26, seq_len=64)
|
| 236 |
+
def prefix_arithmetic_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 237 |
+
return _prefix_arithmetic_impl(seq_len, batch_size, seed)
|
benchmarks/tasks/long_range.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from typing import Generator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from benchmarks.registry import Batch, BatchGenerator, task
|
| 7 |
+
|
| 8 |
+
PAD = 0
|
| 9 |
+
SEP = 1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _copy_at_distance_impl(seq_len: int, batch_size: int, min_filler: int, max_filler: int, seed: int | None = None) -> BatchGenerator:
|
| 13 |
+
rng = random.Random(seed)
|
| 14 |
+
while True:
|
| 15 |
+
batch_input = []
|
| 16 |
+
batch_target = []
|
| 17 |
+
batch_mask = []
|
| 18 |
+
|
| 19 |
+
for _ in range(batch_size):
|
| 20 |
+
data_vocab = list(range(2, 10))
|
| 21 |
+
filler_vocab = list(range(10, 26))
|
| 22 |
+
|
| 23 |
+
data_token = rng.choice(data_vocab)
|
| 24 |
+
|
| 25 |
+
max_filler_allowed = seq_len - 3
|
| 26 |
+
filler_len = rng.randint(min_filler, min(max_filler, max_filler_allowed))
|
| 27 |
+
filler = [rng.choice(filler_vocab) for _ in range(filler_len)]
|
| 28 |
+
|
| 29 |
+
input_seq = [data_token] + filler + [SEP]
|
| 30 |
+
target_seq = filler + [SEP, data_token]
|
| 31 |
+
|
| 32 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 33 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 34 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 35 |
+
|
| 36 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 37 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 38 |
+
|
| 39 |
+
ans_pos = len(input_seq) - 1
|
| 40 |
+
if ans_pos < seq_len:
|
| 41 |
+
loss_mask[ans_pos] = True
|
| 42 |
+
|
| 43 |
+
batch_input.append(input_ids)
|
| 44 |
+
batch_target.append(target_ids)
|
| 45 |
+
batch_mask.append(loss_mask)
|
| 46 |
+
|
| 47 |
+
yield (
|
| 48 |
+
torch.stack(batch_input),
|
| 49 |
+
torch.stack(batch_target),
|
| 50 |
+
torch.stack(batch_mask),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@task("copy_at_distance_64", vocab_size=26, seq_len=64)
|
| 55 |
+
def copy_at_distance_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 56 |
+
return _copy_at_distance_impl(seq_len, batch_size, min_filler=8, max_filler=40, seed=seed)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@task("copy_at_distance_128", vocab_size=26, seq_len=128)
|
| 60 |
+
def copy_at_distance_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 61 |
+
return _copy_at_distance_impl(seq_len, batch_size, min_filler=20, max_filler=100, seed=seed)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _kv_recall_impl(seq_len: int, batch_size: int, min_pairs: int, max_pairs: int, max_filler: int, seed: int | None = None) -> BatchGenerator:
|
| 65 |
+
rng = random.Random(seed)
|
| 66 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 67 |
+
|
| 68 |
+
while True:
|
| 69 |
+
while len(buffer_input) < batch_size:
|
| 70 |
+
n_pairs = rng.randint(min_pairs, max_pairs)
|
| 71 |
+
|
| 72 |
+
key_vocab = list(range(2, 2 + n_pairs + 5))
|
| 73 |
+
val_vocab = list(range(2 + n_pairs + 5, 2 + n_pairs + 5 + n_pairs + 5))
|
| 74 |
+
|
| 75 |
+
keys = rng.sample(key_vocab, n_pairs)
|
| 76 |
+
vals = rng.sample(val_vocab, n_pairs)
|
| 77 |
+
kv_dict = dict(zip(keys, vals))
|
| 78 |
+
|
| 79 |
+
pairs = list(zip(keys, vals))
|
| 80 |
+
|
| 81 |
+
prefix = []
|
| 82 |
+
for k, v in pairs:
|
| 83 |
+
prefix.append(k)
|
| 84 |
+
prefix.append(v)
|
| 85 |
+
if max_filler > 0 and rng.random() < 0.3:
|
| 86 |
+
filler_len = rng.randint(0, max_filler)
|
| 87 |
+
for _ in range(filler_len):
|
| 88 |
+
prefix.append(rng.choice(key_vocab))
|
| 89 |
+
|
| 90 |
+
n_queries = rng.randint(1, n_pairs)
|
| 91 |
+
query_keys = rng.sample(keys, n_queries)
|
| 92 |
+
rng.shuffle(query_keys)
|
| 93 |
+
|
| 94 |
+
answers = [kv_dict[q] for q in query_keys]
|
| 95 |
+
|
| 96 |
+
max_space = seq_len - len(prefix) - 1
|
| 97 |
+
if n_queries * 2 > max_space:
|
| 98 |
+
n_queries = max(1, max_space // 2)
|
| 99 |
+
query_keys = query_keys[:n_queries]
|
| 100 |
+
answers = [kv_dict[q] for q in query_keys]
|
| 101 |
+
|
| 102 |
+
for i in range(len(query_keys)):
|
| 103 |
+
query_part = []
|
| 104 |
+
for j in range(i):
|
| 105 |
+
query_part.append(query_keys[j])
|
| 106 |
+
query_part.append(answers[j])
|
| 107 |
+
query_part.append(query_keys[i])
|
| 108 |
+
|
| 109 |
+
input_seq = prefix + [SEP] + query_part
|
| 110 |
+
target_seq = prefix[1:] + [SEP] + query_part + [answers[i]]
|
| 111 |
+
|
| 112 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 113 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 114 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 115 |
+
|
| 116 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 117 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 118 |
+
|
| 119 |
+
ans_pos = len(input_seq) - 1
|
| 120 |
+
if ans_pos < seq_len:
|
| 121 |
+
loss_mask[ans_pos] = True
|
| 122 |
+
|
| 123 |
+
buffer_input.append(input_ids)
|
| 124 |
+
buffer_target.append(target_ids)
|
| 125 |
+
buffer_mask.append(loss_mask)
|
| 126 |
+
|
| 127 |
+
yield (
|
| 128 |
+
torch.stack(buffer_input[:batch_size]),
|
| 129 |
+
torch.stack(buffer_target[:batch_size]),
|
| 130 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 131 |
+
)
|
| 132 |
+
buffer_input = buffer_input[batch_size:]
|
| 133 |
+
buffer_target = buffer_target[batch_size:]
|
| 134 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@task("kv_recall_64", vocab_size=32, seq_len=64)
|
| 138 |
+
def kv_recall_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 139 |
+
return _kv_recall_impl(seq_len, batch_size, min_pairs=2, max_pairs=5, max_filler=2, seed=seed)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@task("kv_recall_128", vocab_size=32, seq_len=128)
|
| 143 |
+
def kv_recall_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 144 |
+
return _kv_recall_impl(seq_len, batch_size, min_pairs=3, max_pairs=10, max_filler=6, seed=seed)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _needle_in_haystack_impl(seq_len: int, batch_size: int, min_haystack: int, max_haystack: int, seed: int | None = None) -> BatchGenerator:
|
| 148 |
+
rng = random.Random(seed)
|
| 149 |
+
while True:
|
| 150 |
+
batch_input = []
|
| 151 |
+
batch_target = []
|
| 152 |
+
batch_mask = []
|
| 153 |
+
|
| 154 |
+
for _ in range(batch_size):
|
| 155 |
+
key_token = 2
|
| 156 |
+
val_vocab = list(range(3, 19))
|
| 157 |
+
noise_vocab = list(range(19, 51))
|
| 158 |
+
|
| 159 |
+
value = rng.choice(val_vocab)
|
| 160 |
+
|
| 161 |
+
haystack_len = rng.randint(min_haystack, min(max_haystack, seq_len - 4))
|
| 162 |
+
needle_pos = rng.randint(0, haystack_len - 2)
|
| 163 |
+
|
| 164 |
+
haystack = [rng.choice(noise_vocab) for _ in range(haystack_len)]
|
| 165 |
+
haystack[needle_pos] = key_token
|
| 166 |
+
haystack[needle_pos + 1] = value
|
| 167 |
+
|
| 168 |
+
input_seq = haystack + [SEP, key_token]
|
| 169 |
+
target_seq = haystack[1:] + [SEP, key_token, value]
|
| 170 |
+
|
| 171 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 172 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 173 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 174 |
+
|
| 175 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 176 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 177 |
+
|
| 178 |
+
ans_pos = len(input_seq) - 1
|
| 179 |
+
if ans_pos < seq_len:
|
| 180 |
+
loss_mask[ans_pos] = True
|
| 181 |
+
|
| 182 |
+
batch_input.append(input_ids)
|
| 183 |
+
batch_target.append(target_ids)
|
| 184 |
+
batch_mask.append(loss_mask)
|
| 185 |
+
|
| 186 |
+
yield (
|
| 187 |
+
torch.stack(batch_input),
|
| 188 |
+
torch.stack(batch_target),
|
| 189 |
+
torch.stack(batch_mask),
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@task("needle_in_haystack_64", vocab_size=51, seq_len=64)
|
| 194 |
+
def needle_in_haystack_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 195 |
+
return _needle_in_haystack_impl(seq_len, batch_size, min_haystack=16, max_haystack=40, seed=seed)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@task("needle_in_haystack_128", vocab_size=51, seq_len=128)
|
| 199 |
+
def needle_in_haystack_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 200 |
+
return _needle_in_haystack_impl(seq_len, batch_size, min_haystack=16, max_haystack=80, seed=seed)
|
benchmarks/tasks/rule_extraction.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from typing import Generator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from benchmarks.registry import Batch, BatchGenerator, task
|
| 7 |
+
|
| 8 |
+
PAD = 0
|
| 9 |
+
SEP = 1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _period_continuation_impl(seq_len: int, batch_size: int, min_period: int, max_period: int, seed: int | None = None) -> BatchGenerator:
|
| 13 |
+
rng = random.Random(seed)
|
| 14 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 15 |
+
|
| 16 |
+
while True:
|
| 17 |
+
while len(buffer_input) < batch_size:
|
| 18 |
+
period = rng.randint(min_period, max_period)
|
| 19 |
+
n_cycles = rng.randint(2, 4)
|
| 20 |
+
|
| 21 |
+
symbols = list(range(2, 2 + period))
|
| 22 |
+
rng.shuffle(symbols)
|
| 23 |
+
|
| 24 |
+
prefix = []
|
| 25 |
+
for _ in range(n_cycles):
|
| 26 |
+
prefix.extend(symbols)
|
| 27 |
+
|
| 28 |
+
answer = symbols.copy()
|
| 29 |
+
|
| 30 |
+
if len(prefix) + 1 + len(answer) > seq_len:
|
| 31 |
+
period = min_period
|
| 32 |
+
n_cycles = max(2, (seq_len - period - 1) // period)
|
| 33 |
+
symbols = list(range(2, 2 + period))
|
| 34 |
+
rng.shuffle(symbols)
|
| 35 |
+
prefix = []
|
| 36 |
+
for _ in range(n_cycles):
|
| 37 |
+
prefix.extend(symbols)
|
| 38 |
+
answer = symbols.copy()
|
| 39 |
+
|
| 40 |
+
for i in range(len(answer)):
|
| 41 |
+
input_seq = prefix + [SEP] + answer[:i]
|
| 42 |
+
target_seq = prefix[1:] + [SEP] + answer[:i+1]
|
| 43 |
+
|
| 44 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 45 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 46 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 47 |
+
|
| 48 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 49 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 50 |
+
|
| 51 |
+
ans_pos = len(input_seq) - 1
|
| 52 |
+
if ans_pos < seq_len:
|
| 53 |
+
loss_mask[ans_pos] = True
|
| 54 |
+
|
| 55 |
+
buffer_input.append(input_ids)
|
| 56 |
+
buffer_target.append(target_ids)
|
| 57 |
+
buffer_mask.append(loss_mask)
|
| 58 |
+
|
| 59 |
+
yield (
|
| 60 |
+
torch.stack(buffer_input[:batch_size]),
|
| 61 |
+
torch.stack(buffer_target[:batch_size]),
|
| 62 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 63 |
+
)
|
| 64 |
+
buffer_input = buffer_input[batch_size:]
|
| 65 |
+
buffer_target = buffer_target[batch_size:]
|
| 66 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@task("period_continuation_64", vocab_size=14, seq_len=64)
|
| 70 |
+
def period_continuation_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 71 |
+
return _period_continuation_impl(seq_len, batch_size, min_period=2, max_period=6, seed=seed)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@task("period_continuation_128", vocab_size=14, seq_len=128)
|
| 75 |
+
def period_continuation_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 76 |
+
return _period_continuation_impl(seq_len, batch_size, min_period=2, max_period=12, seed=seed)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _finite_state_machine_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 80 |
+
rng = random.Random(seed)
|
| 81 |
+
while True:
|
| 82 |
+
batch_input = []
|
| 83 |
+
batch_target = []
|
| 84 |
+
batch_mask = []
|
| 85 |
+
|
| 86 |
+
for _ in range(batch_size):
|
| 87 |
+
n_states = rng.randint(2, 6)
|
| 88 |
+
n_inputs = rng.randint(2, 4)
|
| 89 |
+
|
| 90 |
+
STATE_START = 2
|
| 91 |
+
INPUT_START = STATE_START + n_states
|
| 92 |
+
|
| 93 |
+
table = {}
|
| 94 |
+
for s in range(n_states):
|
| 95 |
+
for inp in range(n_inputs):
|
| 96 |
+
next_state = rng.randint(0, n_states - 1)
|
| 97 |
+
table[(s, inp)] = next_state
|
| 98 |
+
|
| 99 |
+
table_flat = []
|
| 100 |
+
for s in range(n_states):
|
| 101 |
+
for inp in range(n_inputs):
|
| 102 |
+
table_flat.append(table[(s, inp)] + STATE_START)
|
| 103 |
+
|
| 104 |
+
remaining_len = seq_len - len(table_flat)
|
| 105 |
+
if remaining_len <= 0:
|
| 106 |
+
remaining_len = seq_len // 2
|
| 107 |
+
table_flat = table_flat[:remaining_len // 2]
|
| 108 |
+
|
| 109 |
+
input_stream = [rng.randint(0, n_inputs - 1) + INPUT_START for _ in range(remaining_len)]
|
| 110 |
+
|
| 111 |
+
states = []
|
| 112 |
+
current_state = 0
|
| 113 |
+
for inp in input_stream:
|
| 114 |
+
inp_idx = inp - INPUT_START
|
| 115 |
+
current_state = table[(current_state, inp_idx)]
|
| 116 |
+
states.append(current_state + STATE_START)
|
| 117 |
+
|
| 118 |
+
input_seq = table_flat + input_stream
|
| 119 |
+
target_seq = table_flat[1:] + [input_stream[0]] + states
|
| 120 |
+
|
| 121 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 122 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 123 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 124 |
+
|
| 125 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 126 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 127 |
+
|
| 128 |
+
table_len = len(table_flat)
|
| 129 |
+
for i in range(len(states)):
|
| 130 |
+
pos = table_len + i
|
| 131 |
+
if pos < seq_len:
|
| 132 |
+
loss_mask[pos] = True
|
| 133 |
+
|
| 134 |
+
batch_input.append(input_ids)
|
| 135 |
+
batch_target.append(target_ids)
|
| 136 |
+
batch_mask.append(loss_mask)
|
| 137 |
+
|
| 138 |
+
yield (
|
| 139 |
+
torch.stack(batch_input),
|
| 140 |
+
torch.stack(batch_target),
|
| 141 |
+
torch.stack(batch_mask),
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@task("finite_state_machine_64", vocab_size=16, seq_len=64)
|
| 146 |
+
def finite_state_machine_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 147 |
+
return _finite_state_machine_impl(seq_len, batch_size, seed)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@task("finite_state_machine_128", vocab_size=16, seq_len=128)
|
| 151 |
+
def finite_state_machine_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 152 |
+
return _finite_state_machine_impl(seq_len, batch_size, seed)
|
benchmarks/tasks/short_range.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from typing import Generator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from benchmarks.registry import Batch, BatchGenerator, task
|
| 7 |
+
|
| 8 |
+
PAD = 0
|
| 9 |
+
SEP = 1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _selective_copy_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 13 |
+
rng = random.Random(seed)
|
| 14 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 15 |
+
|
| 16 |
+
while True:
|
| 17 |
+
while len(buffer_input) < batch_size:
|
| 18 |
+
n_copy = rng.randint(2, 6)
|
| 19 |
+
data_vocab_size = rng.randint(4, 10)
|
| 20 |
+
noise_vocab_size = rng.randint(4, 8)
|
| 21 |
+
|
| 22 |
+
target_marker = 2
|
| 23 |
+
data_start = 3
|
| 24 |
+
data_end = data_start + data_vocab_size
|
| 25 |
+
noise_start = data_end
|
| 26 |
+
noise_end = noise_start + noise_vocab_size
|
| 27 |
+
|
| 28 |
+
data_tokens = list(range(data_start, data_end))
|
| 29 |
+
noise_tokens = list(range(noise_start, noise_end))
|
| 30 |
+
|
| 31 |
+
max_slots = (seq_len - 1 - n_copy) // 2
|
| 32 |
+
max_slots = max(n_copy + 1, max_slots)
|
| 33 |
+
n_slots = rng.randint(n_copy + 1, max_slots)
|
| 34 |
+
copy_positions = sorted(rng.sample(range(n_slots), n_copy))
|
| 35 |
+
copy_values = [rng.choice(data_tokens) for _ in range(n_copy)]
|
| 36 |
+
|
| 37 |
+
prefix = []
|
| 38 |
+
copy_idx = 0
|
| 39 |
+
for pos in range(n_slots):
|
| 40 |
+
if copy_idx < n_copy and pos == copy_positions[copy_idx]:
|
| 41 |
+
prefix.extend([target_marker, copy_values[copy_idx]])
|
| 42 |
+
copy_idx += 1
|
| 43 |
+
else:
|
| 44 |
+
prefix.append(rng.choice(data_tokens) if rng.random() < 0.5 else rng.choice(noise_tokens))
|
| 45 |
+
|
| 46 |
+
answer = copy_values
|
| 47 |
+
|
| 48 |
+
for i in range(len(answer)):
|
| 49 |
+
input_seq = prefix + [SEP] + answer[:i]
|
| 50 |
+
target_seq = prefix[1:] + [SEP] + answer[:i+1]
|
| 51 |
+
|
| 52 |
+
if len(input_seq) > seq_len:
|
| 53 |
+
continue
|
| 54 |
+
|
| 55 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 56 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 57 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 58 |
+
|
| 59 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 60 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 61 |
+
|
| 62 |
+
ans_pos = len(input_seq) - 1
|
| 63 |
+
if ans_pos < seq_len:
|
| 64 |
+
loss_mask[ans_pos] = True
|
| 65 |
+
buffer_input.append(input_ids)
|
| 66 |
+
buffer_target.append(target_ids)
|
| 67 |
+
buffer_mask.append(loss_mask)
|
| 68 |
+
|
| 69 |
+
yield (
|
| 70 |
+
torch.stack(buffer_input[:batch_size]),
|
| 71 |
+
torch.stack(buffer_target[:batch_size]),
|
| 72 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 73 |
+
)
|
| 74 |
+
buffer_input = buffer_input[batch_size:]
|
| 75 |
+
buffer_target = buffer_target[batch_size:]
|
| 76 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@task("selective_copy_32", vocab_size=32, seq_len=32)
|
| 80 |
+
def selective_copy_32(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 81 |
+
return _selective_copy_impl(seq_len, batch_size, seed)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@task("selective_copy_64", vocab_size=32, seq_len=64)
|
| 85 |
+
def selective_copy_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 86 |
+
return _selective_copy_impl(seq_len, batch_size, seed)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _reverse_copy_impl(seq_len: int, batch_size: int, min_len: int, max_len: int, seed: int | None = None) -> BatchGenerator:
|
| 90 |
+
rng = random.Random(seed)
|
| 91 |
+
buffer_input, buffer_target, buffer_mask = [], [], []
|
| 92 |
+
|
| 93 |
+
while True:
|
| 94 |
+
while len(buffer_input) < batch_size:
|
| 95 |
+
vocab_size = rng.randint(8, 16)
|
| 96 |
+
data_tokens = list(range(2, 2 + vocab_size))
|
| 97 |
+
|
| 98 |
+
max_seq_len = min(max_len, (seq_len - 1) // 2)
|
| 99 |
+
seq_to_reverse_len = rng.randint(min_len, max_seq_len)
|
| 100 |
+
|
| 101 |
+
sequence = [rng.choice(data_tokens) for _ in range(seq_to_reverse_len)]
|
| 102 |
+
reversed_seq = sequence[::-1]
|
| 103 |
+
|
| 104 |
+
prefix = sequence
|
| 105 |
+
|
| 106 |
+
for i in range(len(reversed_seq)):
|
| 107 |
+
input_seq = prefix + [SEP] + reversed_seq[:i]
|
| 108 |
+
target_seq = prefix[1:] + [SEP] + reversed_seq[:i+1]
|
| 109 |
+
|
| 110 |
+
input_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 111 |
+
target_ids = torch.full((seq_len,), PAD, dtype=torch.long)
|
| 112 |
+
loss_mask = torch.zeros(seq_len, dtype=torch.bool)
|
| 113 |
+
|
| 114 |
+
input_ids[:len(input_seq)] = torch.tensor(input_seq, dtype=torch.long)
|
| 115 |
+
target_ids[:len(target_seq)] = torch.tensor(target_seq, dtype=torch.long)
|
| 116 |
+
|
| 117 |
+
ans_pos = len(input_seq) - 1
|
| 118 |
+
if ans_pos < seq_len:
|
| 119 |
+
loss_mask[ans_pos] = True
|
| 120 |
+
buffer_input.append(input_ids)
|
| 121 |
+
buffer_target.append(target_ids)
|
| 122 |
+
buffer_mask.append(loss_mask)
|
| 123 |
+
|
| 124 |
+
yield (
|
| 125 |
+
torch.stack(buffer_input[:batch_size]),
|
| 126 |
+
torch.stack(buffer_target[:batch_size]),
|
| 127 |
+
torch.stack(buffer_mask[:batch_size]),
|
| 128 |
+
)
|
| 129 |
+
buffer_input = buffer_input[batch_size:]
|
| 130 |
+
buffer_target = buffer_target[batch_size:]
|
| 131 |
+
buffer_mask = buffer_mask[batch_size:]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@task("reverse_copy_32", vocab_size=18, seq_len=32)
|
| 135 |
+
def reverse_copy_32(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 136 |
+
return _reverse_copy_impl(seq_len, batch_size, min_len=3, max_len=10, seed=seed)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@task("reverse_copy_64", vocab_size=18, seq_len=64)
|
| 140 |
+
def reverse_copy_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 141 |
+
return _reverse_copy_impl(seq_len, batch_size, min_len=4, max_len=20, seed=seed)
|
benchmarks/tasks/state.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from typing import Generator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from benchmarks.registry import Batch, BatchGenerator, task
|
| 7 |
+
|
| 8 |
+
PAD = 0
|
| 9 |
+
SEP = 1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _parity_impl(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 13 |
+
rng = random.Random(seed)
|
| 14 |
+
while True:
|
| 15 |
+
batch_input = []
|
| 16 |
+
batch_target = []
|
| 17 |
+
batch_mask = []
|
| 18 |
+
|
| 19 |
+
for _ in range(batch_size):
|
| 20 |
+
bits = [rng.randint(0, 1) + 2 for _ in range(seq_len)]
|
| 21 |
+
|
| 22 |
+
parity = []
|
| 23 |
+
running = 0
|
| 24 |
+
for bit in bits:
|
| 25 |
+
running ^= (bit - 2)
|
| 26 |
+
parity.append(running + 2)
|
| 27 |
+
|
| 28 |
+
input_ids = torch.tensor(bits, dtype=torch.long)
|
| 29 |
+
target_ids = torch.tensor(parity, dtype=torch.long)
|
| 30 |
+
loss_mask = torch.ones(seq_len, dtype=torch.bool)
|
| 31 |
+
|
| 32 |
+
batch_input.append(input_ids)
|
| 33 |
+
batch_target.append(target_ids)
|
| 34 |
+
batch_mask.append(loss_mask)
|
| 35 |
+
|
| 36 |
+
yield (
|
| 37 |
+
torch.stack(batch_input),
|
| 38 |
+
torch.stack(batch_target),
|
| 39 |
+
torch.stack(batch_mask),
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@task("parity_64", vocab_size=4, seq_len=64)
|
| 44 |
+
def parity_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 45 |
+
return _parity_impl(seq_len, batch_size, seed)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@task("parity_128", vocab_size=4, seq_len=128)
|
| 49 |
+
def parity_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 50 |
+
return _parity_impl(seq_len, batch_size, seed)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _running_sum_mod_n_impl(seq_len: int, batch_size: int, n: int, seed: int | None = None) -> BatchGenerator:
|
| 54 |
+
rng = random.Random(seed)
|
| 55 |
+
while True:
|
| 56 |
+
batch_input = []
|
| 57 |
+
batch_target = []
|
| 58 |
+
batch_mask = []
|
| 59 |
+
|
| 60 |
+
for _ in range(batch_size):
|
| 61 |
+
tokens = [rng.randint(0, n - 1) + 2 for _ in range(seq_len)]
|
| 62 |
+
|
| 63 |
+
running_sums = []
|
| 64 |
+
running = 0
|
| 65 |
+
for tok in tokens:
|
| 66 |
+
running = (running + (tok - 2)) % n
|
| 67 |
+
running_sums.append(running + 2)
|
| 68 |
+
|
| 69 |
+
input_ids = torch.tensor(tokens, dtype=torch.long)
|
| 70 |
+
target_ids = torch.tensor(running_sums, dtype=torch.long)
|
| 71 |
+
loss_mask = torch.ones(seq_len, dtype=torch.bool)
|
| 72 |
+
|
| 73 |
+
batch_input.append(input_ids)
|
| 74 |
+
batch_target.append(target_ids)
|
| 75 |
+
batch_mask.append(loss_mask)
|
| 76 |
+
|
| 77 |
+
yield (
|
| 78 |
+
torch.stack(batch_input),
|
| 79 |
+
torch.stack(batch_target),
|
| 80 |
+
torch.stack(batch_mask),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@task("running_sum_mod8_64", vocab_size=10, seq_len=64)
|
| 85 |
+
def running_sum_mod8_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 86 |
+
return _running_sum_mod_n_impl(seq_len, batch_size, n=8, seed=seed)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@task("running_sum_mod8_128", vocab_size=10, seq_len=128)
|
| 90 |
+
def running_sum_mod8_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 91 |
+
return _running_sum_mod_n_impl(seq_len, batch_size, n=8, seed=seed)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@task("running_sum_mod16_64", vocab_size=18, seq_len=64)
|
| 95 |
+
def running_sum_mod16_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 96 |
+
return _running_sum_mod_n_impl(seq_len, batch_size, n=16, seed=seed)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@task("running_sum_mod16_128", vocab_size=18, seq_len=128)
|
| 100 |
+
def running_sum_mod16_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 101 |
+
return _running_sum_mod_n_impl(seq_len, batch_size, n=16, seed=seed)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _delta_tracking_impl(seq_len: int, batch_size: int, cap: int, seed: int | None = None) -> BatchGenerator:
|
| 105 |
+
rng = random.Random(seed)
|
| 106 |
+
while True:
|
| 107 |
+
batch_input = []
|
| 108 |
+
batch_target = []
|
| 109 |
+
batch_mask = []
|
| 110 |
+
|
| 111 |
+
MINUS = 2
|
| 112 |
+
PLUS = 3
|
| 113 |
+
COUNT_START = 4
|
| 114 |
+
|
| 115 |
+
for _ in range(batch_size):
|
| 116 |
+
deltas = []
|
| 117 |
+
counts = []
|
| 118 |
+
current = cap // 2
|
| 119 |
+
|
| 120 |
+
for _ in range(seq_len):
|
| 121 |
+
if current <= 0:
|
| 122 |
+
delta = rng.choices([-1, 1], weights=[0.2, 0.8])[0]
|
| 123 |
+
elif current >= cap:
|
| 124 |
+
delta = rng.choices([-1, 1], weights=[0.8, 0.2])[0]
|
| 125 |
+
else:
|
| 126 |
+
delta = rng.choice([-1, 1])
|
| 127 |
+
|
| 128 |
+
deltas.append(PLUS if delta == 1 else MINUS)
|
| 129 |
+
current = max(0, min(cap, current + delta))
|
| 130 |
+
counts.append(current + COUNT_START)
|
| 131 |
+
|
| 132 |
+
input_ids = torch.tensor(deltas, dtype=torch.long)
|
| 133 |
+
target_ids = torch.tensor(counts, dtype=torch.long)
|
| 134 |
+
loss_mask = torch.ones(seq_len, dtype=torch.bool)
|
| 135 |
+
|
| 136 |
+
batch_input.append(input_ids)
|
| 137 |
+
batch_target.append(target_ids)
|
| 138 |
+
batch_mask.append(loss_mask)
|
| 139 |
+
|
| 140 |
+
yield (
|
| 141 |
+
torch.stack(batch_input),
|
| 142 |
+
torch.stack(batch_target),
|
| 143 |
+
torch.stack(batch_mask),
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@task("delta_tracking_64", vocab_size=12, seq_len=64)
|
| 148 |
+
def delta_tracking_64(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 149 |
+
return _delta_tracking_impl(seq_len, batch_size, cap=8, seed=seed)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@task("delta_tracking_128", vocab_size=12, seq_len=128)
|
| 153 |
+
def delta_tracking_128(seq_len: int, batch_size: int, seed: int | None = None) -> BatchGenerator:
|
| 154 |
+
return _delta_tracking_impl(seq_len, batch_size, cap=8, seed=seed)
|
deploy/README.md
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Deploy
|
| 2 |
+
|
| 3 |
+
This folder contains some small scripts for deploying the language models trained with this repository to some
|
| 4 |
+
small use cases (Terminal CLI, small GUI, Discord bot, OpenAI API, etc).
|
module/README.md
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Module
|
| 2 |
+
|
| 3 |
+
This is where the brunt of the repository work goes. This is a collection of torch nn.Modules and other various
|
| 4 |
+
things, and is where most of the experimentation and research is actually done.
|
module/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from module.transformers.moe.moe import MoE
|
| 2 |
+
from module.transformers.moe.transformer_block import MoEVanillaTransformerBlock
|
| 3 |
+
from module.transformers.rope.multi_head_attention import RoPEVanillaMultiHeadAttention
|
| 4 |
+
from module.transformers.rope.rope import RoPE
|
| 5 |
+
from module.transformers.rope.transformer_block import RoPEVanillaTransformerBlock
|
| 6 |
+
from module.transformers.vanilla.multi_head_attention import VanillaMultiHeadAttention
|
| 7 |
+
from module.transformers.vanilla.transformer_block import VanillaTransformerBlock
|
module/transformers/__init__.py
ADDED
|
File without changes
|
module/transformers/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (155 Bytes). View file
|
|
|
module/transformers/moe/__init__.py
ADDED
|
File without changes
|
module/transformers/moe/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (159 Bytes). View file
|
|
|
module/transformers/moe/__pycache__/moe.cpython-313.pyc
ADDED
|
Binary file (4.64 kB). View file
|
|
|
module/transformers/moe/__pycache__/moe_rope_transformer_block.cpython-313.pyc
ADDED
|
Binary file (3.18 kB). View file
|
|
|
module/transformers/moe/__pycache__/transformer_block.cpython-313.pyc
ADDED
|
Binary file (3.16 kB). View file
|
|
|