Spaces:
Sleeping
Sleeping
Borzyszkowski commited on
Commit ·
bb2fa48
1
Parent(s): 99a9f7b
ALP-1: web app for Alpine LLM'
Browse files- .gitignore +211 -0
- README.md +1 -1
- app.py +84 -69
- config_util.py +34 -0
- demo_inference.py +55 -0
- model/transformer_decoder.py +166 -0
- requirements.txt +4 -0
- tokenizer.py +21 -0
.gitignore
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# SageMath parsed files
|
| 135 |
+
*.sage.py
|
| 136 |
+
|
| 137 |
+
# Environments
|
| 138 |
+
.env
|
| 139 |
+
.envrc
|
| 140 |
+
.venv
|
| 141 |
+
env/
|
| 142 |
+
venv/
|
| 143 |
+
ENV/
|
| 144 |
+
env.bak/
|
| 145 |
+
venv.bak/
|
| 146 |
+
|
| 147 |
+
# Spyder project settings
|
| 148 |
+
.spyderproject
|
| 149 |
+
.spyproject
|
| 150 |
+
|
| 151 |
+
# Rope project settings
|
| 152 |
+
.ropeproject
|
| 153 |
+
|
| 154 |
+
# mkdocs documentation
|
| 155 |
+
/site
|
| 156 |
+
|
| 157 |
+
# mypy
|
| 158 |
+
.mypy_cache/
|
| 159 |
+
.dmypy.json
|
| 160 |
+
dmypy.json
|
| 161 |
+
|
| 162 |
+
# Pyre type checker
|
| 163 |
+
.pyre/
|
| 164 |
+
|
| 165 |
+
# pytype static type analyzer
|
| 166 |
+
.pytype/
|
| 167 |
+
|
| 168 |
+
# Cython debug symbols
|
| 169 |
+
cython_debug/
|
| 170 |
+
|
| 171 |
+
# PyCharm
|
| 172 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
| 173 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
| 174 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
| 175 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
| 176 |
+
#.idea/
|
| 177 |
+
|
| 178 |
+
# Abstra
|
| 179 |
+
# Abstra is an AI-powered process automation framework.
|
| 180 |
+
# Ignore directories containing user credentials, local state, and settings.
|
| 181 |
+
# Learn more at https://abstra.io/docs
|
| 182 |
+
.abstra/
|
| 183 |
+
|
| 184 |
+
# Visual Studio Code
|
| 185 |
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
| 186 |
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
| 187 |
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
| 188 |
+
# you could uncomment the following to ignore the entire vscode folder
|
| 189 |
+
# .vscode/
|
| 190 |
+
|
| 191 |
+
# Ruff stuff:
|
| 192 |
+
.ruff_cache/
|
| 193 |
+
|
| 194 |
+
# PyPI configuration file
|
| 195 |
+
.pypirc
|
| 196 |
+
|
| 197 |
+
# Cursor
|
| 198 |
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
| 199 |
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
| 200 |
+
# refer to https://docs.cursor.com/context/ignore-files
|
| 201 |
+
.cursorignore
|
| 202 |
+
.cursorindexingignore
|
| 203 |
+
|
| 204 |
+
# Marimo
|
| 205 |
+
marimo/_static/
|
| 206 |
+
marimo/_lsp/
|
| 207 |
+
__marimo__/
|
| 208 |
+
|
| 209 |
+
# Other custom ignores
|
| 210 |
+
best_model
|
| 211 |
+
model-cache
|
README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
---
|
| 2 |
-
title: AlpineLLM
|
| 3 |
emoji: 💬
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: purple
|
|
|
|
| 1 |
---
|
| 2 |
+
title: AlpineLLM-App
|
| 3 |
emoji: 💬
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: purple
|
app.py
CHANGED
|
@@ -1,70 +1,85 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" A simple Gradio web app to interact with the AlpineLLM model """
|
| 2 |
+
|
| 3 |
import gradio as gr
|
| 4 |
+
import os
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from huggingface_hub import hf_hub_download
|
| 8 |
+
|
| 9 |
+
from demo_inference import AlpineLLMInference
|
| 10 |
+
from config_util import Config
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def download_model(cfg):
|
| 14 |
+
""" Download the model weights from Hugging Face Hub """
|
| 15 |
+
model_path = hf_hub_download(
|
| 16 |
+
repo_id=cfg.repo_id,
|
| 17 |
+
filename=cfg.model_name,
|
| 18 |
+
cache_dir="./model-cache"
|
| 19 |
+
)
|
| 20 |
+
return model_path
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def start_app():
|
| 24 |
+
""" Start the web app via Gradio with custom layout """
|
| 25 |
+
with gr.Blocks(css="""#builtwithgradio, .footer, .svelte-1ipelgc {display: none !important;}""") as app:
|
| 26 |
+
gr.Markdown("<h1 style='text-align: center;'> AlpineLLM App</h1>")
|
| 27 |
+
gr.Markdown(
|
| 28 |
+
"<p style='text-align: center;'>"
|
| 29 |
+
"A domain-specific language model for alpine storytelling. <br>"
|
| 30 |
+
"Generate climbing stories, mountain impressions, and expedition-style text."
|
| 31 |
+
"</p>"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
with gr.Row():
|
| 35 |
+
with gr.Column(scale=1):
|
| 36 |
+
prompt = gr.Textbox(
|
| 37 |
+
lines=8,
|
| 38 |
+
label="Your alpine prompt...",
|
| 39 |
+
placeholder="A dawn climb on the Matterhorn..."
|
| 40 |
+
)
|
| 41 |
+
max_tokens = gr.Slider(50, 1000, value=300, step=10, label="Max output tokens")
|
| 42 |
+
generate_btn = gr.Button("🚀 Generate")
|
| 43 |
+
|
| 44 |
+
with gr.Column(scale=2):
|
| 45 |
+
output = gr.Textbox(lines=20, label="Generated Alpine Story", interactive=False)
|
| 46 |
+
|
| 47 |
+
# Bind button click to inference
|
| 48 |
+
generate_btn.click(
|
| 49 |
+
fn=inference.generate_text,
|
| 50 |
+
inputs=[prompt, max_tokens],
|
| 51 |
+
outputs=output
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if __name__ == '__main__':
|
| 58 |
+
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
| 59 |
+
|
| 60 |
+
# Define the configuration
|
| 61 |
+
cfg = {
|
| 62 |
+
'cuda_id': 0,
|
| 63 |
+
'model_type': 'transformer',
|
| 64 |
+
'repo_id': "Borzyszkowski/AlpineLLM-model",
|
| 65 |
+
'model_name': "best_model",
|
| 66 |
+
}
|
| 67 |
+
cfg = Config(cfg)
|
| 68 |
+
|
| 69 |
+
# Define the hyperparameters
|
| 70 |
+
hyperparam_cfg={
|
| 71 |
+
"embedding_dim": 384,
|
| 72 |
+
"num_heads": 6,
|
| 73 |
+
"num_layers": 6,
|
| 74 |
+
"dropout": 0.2,
|
| 75 |
+
"context_len": 256,
|
| 76 |
+
"lr": 3e-4,
|
| 77 |
+
}
|
| 78 |
+
hyperparam_cfg = Config(hyperparam_cfg)
|
| 79 |
+
|
| 80 |
+
# Ensure model weights are available
|
| 81 |
+
cfg.load_weights_path = download_model(cfg)
|
| 82 |
+
|
| 83 |
+
# Start the application
|
| 84 |
+
inference = AlpineLLMInference(cfg, hyperparam_cfg)
|
| 85 |
+
start_app()
|
config_util.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Config utility """
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import yaml
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Config(dict):
|
| 8 |
+
""" Parser for the .yaml configuration files"""
|
| 9 |
+
def __init__(self, config, user_cfg_path=None):
|
| 10 |
+
user_config = self.load_cfg(user_cfg_path) if user_cfg_path else {}
|
| 11 |
+
|
| 12 |
+
# Update default_cfg with user_config (overwriting defaults if needed)
|
| 13 |
+
config.update(user_config)
|
| 14 |
+
super().__init__(config)
|
| 15 |
+
|
| 16 |
+
def load_cfg(self, load_path):
|
| 17 |
+
with open(load_path, "r") as infile:
|
| 18 |
+
cfg = yaml.safe_load(infile)
|
| 19 |
+
return cfg if cfg is not None else {}
|
| 20 |
+
|
| 21 |
+
def write_cfg(self, write_path):
|
| 22 |
+
os.makedirs(os.path.dirname(write_path), exist_ok=True)
|
| 23 |
+
dump_dict = {k: v for k, v in self.items() if k != "default_cfg"}
|
| 24 |
+
with open(write_path, "w") as outfile:
|
| 25 |
+
yaml.safe_dump(dump_dict, outfile, default_flow_style=False)
|
| 26 |
+
|
| 27 |
+
def __getattr__(self, key):
|
| 28 |
+
try:
|
| 29 |
+
return self[key]
|
| 30 |
+
except KeyError:
|
| 31 |
+
raise AttributeError(key)
|
| 32 |
+
|
| 33 |
+
__setattr__ = dict.__setitem__
|
| 34 |
+
__delattr__ = dict.__delitem__
|
demo_inference.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Lightweight inference wrapper for the demo application """
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from tokenizer import CharacterLevelTokenizer
|
| 7 |
+
from model.transformer_decoder import TransformerDecoder
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AlpineLLMInference:
|
| 11 |
+
def __init__(self, cfg, hyperparam_cfg):
|
| 12 |
+
self.cfg = cfg
|
| 13 |
+
self.hyperparam_cfg = hyperparam_cfg
|
| 14 |
+
self.device = torch.device(f"cuda:{self.cfg.cuda_id}" if torch.cuda.is_available() else "cpu")
|
| 15 |
+
self.tokenizer = CharacterLevelTokenizer()
|
| 16 |
+
self.model = self.select_model()
|
| 17 |
+
self.get_model(cfg.load_weights_path)
|
| 18 |
+
|
| 19 |
+
def run_demo(self):
|
| 20 |
+
""" Run a simple demo loop to generate text based on user input """
|
| 21 |
+
while True:
|
| 22 |
+
prompt = input("Enter a prompt (or 'exit' to quit): ")
|
| 23 |
+
if prompt.lower() == 'exit':
|
| 24 |
+
logging.info("Exiting the demo.")
|
| 25 |
+
break
|
| 26 |
+
generated_text = self.generate_text(prompt)
|
| 27 |
+
logging.info(f"Generated Text:\n{generated_text}\n")
|
| 28 |
+
|
| 29 |
+
@torch.no_grad()
|
| 30 |
+
def generate_text(self, prompt, max_new_tokens):
|
| 31 |
+
# tokenize input
|
| 32 |
+
input_ids = torch.tensor([self.tokenizer.encode(prompt)], device=self.device)
|
| 33 |
+
# generate tokens
|
| 34 |
+
output_ids = self.model.generate(input_ids, max_new_tokens=max_new_tokens)
|
| 35 |
+
# decode to string
|
| 36 |
+
return self.tokenizer.decode(output_ids[0].tolist())
|
| 37 |
+
|
| 38 |
+
def select_model(self):
|
| 39 |
+
""" Selects the neural network architecture based on the desired configuration """
|
| 40 |
+
vocab_size = len(self.tokenizer.vocab)
|
| 41 |
+
if self.cfg.model_type == 'transformer':
|
| 42 |
+
model = TransformerDecoder(vocab_size=vocab_size,
|
| 43 |
+
hyperparam_cfg=self.hyperparam_cfg,
|
| 44 |
+
device=self.device).to(self.device)
|
| 45 |
+
else:
|
| 46 |
+
raise ValueError(f"Model type '{self.cfg.model_type}' is not supported!")
|
| 47 |
+
model_name = model.__class__.__name__
|
| 48 |
+
logging.info(f'Selected model type: {self.cfg.model_type} with name: {model_name}')
|
| 49 |
+
return model
|
| 50 |
+
|
| 51 |
+
def get_model(self, model_path):
|
| 52 |
+
""" Loads weights of the model from the specified path """
|
| 53 |
+
checkpoint = torch.load(model_path, map_location=self.device)
|
| 54 |
+
self.model.load_state_dict(checkpoint[0], strict=False)
|
| 55 |
+
logging.info(f'Restored model from: {model_path}')
|
model/transformer_decoder.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Architecture of the TransformerDecoder """
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TransformerDecoder(nn.Module):
|
| 9 |
+
""" GPT-style decoder-only language model """
|
| 10 |
+
|
| 11 |
+
def __init__(self, vocab_size, hyperparam_cfg, device):
|
| 12 |
+
super(TransformerDecoder, self).__init__()
|
| 13 |
+
self.device = device
|
| 14 |
+
|
| 15 |
+
# model hyperparameters
|
| 16 |
+
embedding_dim = hyperparam_cfg.embedding_dim
|
| 17 |
+
num_layers = hyperparam_cfg.num_layers
|
| 18 |
+
self.context_len = hyperparam_cfg.context_len
|
| 19 |
+
|
| 20 |
+
# lookup table of tokens is used so that each token reads the logits for the next token
|
| 21 |
+
self.token_embedding_table = nn.Embedding(vocab_size, embedding_dim)
|
| 22 |
+
# pos embedding table adds information about the position of each token in the context
|
| 23 |
+
self.pos_embedding_table = nn.Embedding(self.context_len, embedding_dim)
|
| 24 |
+
# stack multiple transformer blocks to increase model capacity
|
| 25 |
+
self.tfblocks = nn.Sequential(*[TFBlock(hyperparam_cfg) for _ in range(num_layers)])
|
| 26 |
+
# final normalization and linear layer to produce logits for each token in the vocabulary
|
| 27 |
+
self.ln_f = nn.LayerNorm(embedding_dim)
|
| 28 |
+
self.lm_head = nn.Linear(embedding_dim, vocab_size)
|
| 29 |
+
|
| 30 |
+
# better weight initialization for
|
| 31 |
+
self.apply(self._init_weights)
|
| 32 |
+
|
| 33 |
+
def _init_weights(self, module):
|
| 34 |
+
if isinstance(module, nn.Linear):
|
| 35 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 36 |
+
if module.bias is not None:
|
| 37 |
+
torch.nn.init.zeros_(module.bias)
|
| 38 |
+
elif isinstance(module, nn.Embedding):
|
| 39 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 40 |
+
|
| 41 |
+
def forward(self, idx):
|
| 42 |
+
"""
|
| 43 |
+
The forward pass of the model returns the logits of shape (B,T,C)
|
| 44 |
+
# where: B=batch_size T=context_len C=vocab_size
|
| 45 |
+
"""
|
| 46 |
+
# idx is a (B,T) tensor of integers which are indices in the current context
|
| 47 |
+
B, T = idx.shape
|
| 48 |
+
token_embd = self.token_embedding_table(idx) # (batch_size, context_len, embedding_dim)
|
| 49 |
+
positions = torch.arange(T).to(self.device) # tensor([0, 1, 2, ..., T-1])
|
| 50 |
+
pos_embd = self.pos_embedding_table(positions) # (context_len, embedding_dim)
|
| 51 |
+
x = token_embd + pos_embd # (batch_size, context_len, embedding_dim)
|
| 52 |
+
x = self.tfblocks(x) # (batch_size, context_len, embedding_dim)
|
| 53 |
+
x = self.ln_f(x) # (batch_size, context_len, embedding_dim)
|
| 54 |
+
logits = self.lm_head(x) # (batch_size, context_len, vocab_size)
|
| 55 |
+
return logits
|
| 56 |
+
|
| 57 |
+
def generate(self, idx, max_new_tokens):
|
| 58 |
+
""" Generate new tokens from the model """
|
| 59 |
+
for _ in range(max_new_tokens):
|
| 60 |
+
# crop idx to the last context_len tokens
|
| 61 |
+
idx_context = idx[:, -self.context_len:]
|
| 62 |
+
# get the predictions
|
| 63 |
+
logits = self(idx_context) # (B,T,C)
|
| 64 |
+
# focus only on the last time step
|
| 65 |
+
logits = logits[:, -1, :] # (B, C)
|
| 66 |
+
# apply softmax to get probabilities
|
| 67 |
+
probs = F.softmax(logits, dim=-1) # (B, C)
|
| 68 |
+
# sample from the distribution to get the next token index
|
| 69 |
+
idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
|
| 70 |
+
# append sampled index to the running sequence
|
| 71 |
+
idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
|
| 72 |
+
return idx
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TFBlock(nn.Module):
|
| 76 |
+
""" Single transformer block: communication (attention) followed by computation (dense) """
|
| 77 |
+
|
| 78 |
+
def __init__(self, hyperparam_cfg):
|
| 79 |
+
super(TFBlock, self).__init__()
|
| 80 |
+
|
| 81 |
+
# model hyperparameters
|
| 82 |
+
embedding_dim = hyperparam_cfg.embedding_dim
|
| 83 |
+
num_heads = hyperparam_cfg.num_heads
|
| 84 |
+
context_len = hyperparam_cfg.context_len
|
| 85 |
+
dropout = hyperparam_cfg.dropout
|
| 86 |
+
|
| 87 |
+
# size of MultiHeadAttention matches the embedding dimension (num_heads * head_size = embedding_dim)
|
| 88 |
+
self.sa_heads = MultiHeadAttention(num_heads=num_heads,
|
| 89 |
+
head_size=embedding_dim // num_heads,
|
| 90 |
+
embedding_dim=embedding_dim,
|
| 91 |
+
context_len=context_len,
|
| 92 |
+
dropout=dropout)
|
| 93 |
+
self.feed_forward = FeedForward(embedding_dim, dropout)
|
| 94 |
+
self.ln1 = nn.LayerNorm(embedding_dim)
|
| 95 |
+
self.ln2 = nn.LayerNorm(embedding_dim)
|
| 96 |
+
|
| 97 |
+
def forward(self, x):
|
| 98 |
+
# both attention and feed-forward layers have residual connections
|
| 99 |
+
x = x + self.sa_heads(self.ln1(x))
|
| 100 |
+
x = x + self.feed_forward(self.ln2(x))
|
| 101 |
+
return x
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class MultiHeadAttention(nn.Module):
|
| 105 |
+
""" Multiple heads of self-attention in parallel """
|
| 106 |
+
|
| 107 |
+
def __init__(self, num_heads, head_size, embedding_dim, context_len, dropout):
|
| 108 |
+
super(MultiHeadAttention, self).__init__()
|
| 109 |
+
self.heads = nn.ModuleList([AttentionHead(embedding_dim, head_size, context_len, dropout) for _ in range(num_heads)])
|
| 110 |
+
# projection is needed due to residual connection to bring all heads back to embedding_dim
|
| 111 |
+
self.projection = nn.Linear(num_heads * head_size, embedding_dim)
|
| 112 |
+
self.dropout = nn.Dropout(dropout)
|
| 113 |
+
|
| 114 |
+
def forward(self, x):
|
| 115 |
+
x = torch.cat([h(x) for h in self.heads], dim=-1) # (batch, context_len, num_heads * head_size)
|
| 116 |
+
out = self.dropout(self.projection(x)) # (batch, context_len, embedding_dim)
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class AttentionHead(nn.Module):
|
| 121 |
+
""" One head of self-attention """
|
| 122 |
+
|
| 123 |
+
def __init__(self, embedding_dim, head_size, context_len, dropout):
|
| 124 |
+
super(AttentionHead, self).__init__()
|
| 125 |
+
self.queries = nn.Linear(embedding_dim, head_size, bias=False)
|
| 126 |
+
self.keys = nn.Linear(embedding_dim, head_size, bias=False)
|
| 127 |
+
self.values = nn.Linear(embedding_dim, head_size, bias=False)
|
| 128 |
+
self.dropout = nn.Dropout(dropout)
|
| 129 |
+
|
| 130 |
+
# lower triangular matrix is used to mask out future tokens in the attention mechanism
|
| 131 |
+
self.register_buffer("mask", torch.tril(torch.ones(context_len, context_len)))
|
| 132 |
+
|
| 133 |
+
def forward(self, x):
|
| 134 |
+
B, T, C = x.shape # (batch_size, context_len, embedding_dim)
|
| 135 |
+
q = self.queries(x) # (batch, context_len, head_size)
|
| 136 |
+
k = self.keys(x) # (batch, context_len, head_size)
|
| 137 |
+
v = self.values(x) # (batch, context_len, head_size)
|
| 138 |
+
|
| 139 |
+
# compute attention matrix (key and query dot product)
|
| 140 |
+
weights = q @ k.transpose(-2, -1) # (B,T,C) @ (B,C,T) -> (B,T,T)
|
| 141 |
+
# scale by sqrt(head_size) to prevent large dot products (stabilizes gradients)
|
| 142 |
+
weights = weights * C**-0.5
|
| 143 |
+
# mask replaces 0 with -inf and keeps 1 as is (ones are on and below diagonal; zeros above diagonal)
|
| 144 |
+
weights = weights.masked_fill(self.mask[:T, :T] == 0, float('-inf'))
|
| 145 |
+
# softmax along the last dimension to get probabilities per row
|
| 146 |
+
weights = F.softmax(weights, dim=-1)
|
| 147 |
+
weights = self.dropout(weights)
|
| 148 |
+
output = weights @ v # matrix multiplication (T,T) @ (B,T,C) -> (B,T,C) = (batch, context_len, head_size)
|
| 149 |
+
return output
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class FeedForward(nn.Module):
|
| 153 |
+
""" Single feed-forward layer followed by a non-linearity """
|
| 154 |
+
|
| 155 |
+
def __init__(self, embedding_dim, dropout):
|
| 156 |
+
super(FeedForward, self).__init__()
|
| 157 |
+
# embedding_dim is multiplied by 4 to reflect the original transformer paper
|
| 158 |
+
self.net = nn.Sequential(
|
| 159 |
+
nn.Linear(embedding_dim, embedding_dim * 4),
|
| 160 |
+
nn.ReLU(),
|
| 161 |
+
nn.Linear(embedding_dim * 4, embedding_dim),
|
| 162 |
+
nn.Dropout(dropout)
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def forward(self, x):
|
| 166 |
+
return self.net(x)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.47.2
|
| 2 |
+
huggingface-hub==0.35.3
|
| 3 |
+
pyyaml==6.0.2
|
| 4 |
+
torch==2.4.1
|
tokenizer.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Collection of tokenizers for text data. """
|
| 2 |
+
|
| 3 |
+
import string
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class CharacterLevelTokenizer:
|
| 7 |
+
""" A simple character-level tokenizer for text data. """
|
| 8 |
+
|
| 9 |
+
def __init__(self):
|
| 10 |
+
""" Initializes the tokenizer by creating a vocabulary of unique characters """
|
| 11 |
+
self.vocab = sorted(set(string.ascii_letters + string.digits + string.punctuation + " \n"))
|
| 12 |
+
self.token_to_id = {token: idx for idx, token in enumerate(self.vocab)}
|
| 13 |
+
self.id_to_token = {idx: token for idx, token in enumerate(self.vocab)}
|
| 14 |
+
|
| 15 |
+
def encode(self, str_input):
|
| 16 |
+
""" encoder: take a string, output a list of integers """
|
| 17 |
+
return [self.token_to_id[token] for token in str_input]
|
| 18 |
+
|
| 19 |
+
def decode(self, token_ids):
|
| 20 |
+
""" decoder: take a list of integers, output a string """
|
| 21 |
+
return ''.join([self.id_to_token[token_id] for token_id in token_ids])
|