First commit
commit
a13f526f87
@ -0,0 +1,2 @@
|
||||
data/
|
||||
logs/
|
||||
@ -0,0 +1,2 @@
|
||||
*.pq filter=lfs diff=lfs merge=lfs -text
|
||||
*.csv filter=lfs diff=lfs merge=lfs -text
|
||||
@ -0,0 +1,219 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
# Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
# poetry.lock
|
||||
# poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||
# pdm.lock
|
||||
# pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# pixi
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||
# pixi.lock
|
||||
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||
.pixi
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# Redis
|
||||
*.rdb
|
||||
*.aof
|
||||
*.pid
|
||||
|
||||
# RabbitMQ
|
||||
mnesia/
|
||||
rabbitmq/
|
||||
rabbitmq-data/
|
||||
|
||||
# ActiveMQ
|
||||
activemq-data/
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
# .idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
# Streamlit
|
||||
.streamlit/secrets.toml
|
||||
|
||||
logs/
|
||||
data/
|
||||
@ -0,0 +1,51 @@
|
||||
FROM pytorch/pytorch:2.6.0-cuda12.6-cudnn9-runtime
|
||||
ENV TZ=Europe/Samara
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
|
||||
ARG USER
|
||||
ARG GROUP
|
||||
ARG UID
|
||||
ARG GID
|
||||
|
||||
RUN apt update
|
||||
RUN apt install sudo -y
|
||||
RUN sed -i 's/^%sudo.*/%sudo ALL=(ALL) NOPASSWD: ALL/' /etc/sudoers
|
||||
|
||||
RUN groupadd --gid ${GID} ${GROUP}
|
||||
RUN useradd --shell /bin/bash --uid ${UID} --gid ${GID} -G sudo --create-home ${USER}
|
||||
RUN mkdir /wd
|
||||
RUN chown ${USER}:${GROUP} /wd
|
||||
|
||||
# SYSTEM CONFIGURATION
|
||||
RUN apt install wget vim htop mc git tree -y
|
||||
RUN apt-get install -y libssl-dev autoconf libtool make
|
||||
RUN cd /usr/local/src && \
|
||||
wget https://curl.haxx.se/download/curl-7.88.1.zip && \
|
||||
unzip curl-7.88.1.zip && \
|
||||
cd curl-7.88.1 && \
|
||||
./buildconf && \
|
||||
./configure --with-ssl && \
|
||||
make && \
|
||||
make install && \
|
||||
cp /usr/local/bin/curl /usr/bin/curl && \
|
||||
ldconfig && \
|
||||
curl -V
|
||||
RUN curl -fsSL https://code-server.dev/install.sh | sh
|
||||
RUN /opt/conda/bin/conda install -n base ipykernel --update-deps --force-reinstall -y
|
||||
|
||||
USER ${USER}
|
||||
|
||||
# USER CONFIGURATION
|
||||
RUN pip install schedulefree tensorboard opencv-python-headless scipy pandas matplotlib torchmetrics pyarrow einops nvitop
|
||||
|
||||
RUN openssl req -x509 -newkey rsa:4096 -keyout /home/${USER}/key.pem -out /home/${USER}/cert.pem -sha256 -nodes -days 365 -subj "/C=RU/ST=SamaraRegion/L=Samara/O=SSAU/OU=LIAV/CN=vscode.ssau.ru/"
|
||||
RUN mkdir -p /home/${USER}/.config/code-server
|
||||
RUN echo 'bind-addr: 0.0.0.0:8443' >> /home/${USER}/.config/code-server/config.yaml
|
||||
RUN echo "cert: /home/${USER}/cert.pem" >> /home/${USER}/.config/code-server/config.yaml
|
||||
RUN echo "cert-key: /home/${USER}/key.pem" >> /home/${USER}/.config/code-server/config.yaml
|
||||
|
||||
RUN code-server --install-extension ms-python.python
|
||||
|
||||
ENV SHELL=/bin/bash
|
||||
SHELL ["/bin/bash", "--login", "-i", "-c"]
|
||||
WORKDIR /wd
|
||||
@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
CURDIRNAME=${PWD##*/}
|
||||
|
||||
docker build . -t ${USER}_${CURDIRNAME}_vscode \
|
||||
--build-arg USER=${USER} \
|
||||
--build-arg GROUP=${USER} \
|
||||
--build-arg UID=$(id -u ${USER}) \
|
||||
--build-arg GID=$(id -g ${USER})
|
||||
@ -0,0 +1,115 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.nn import functional as F
|
||||
from einops import rearrange
|
||||
import numpy as np
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
from datetime import datetime
|
||||
import sys
|
||||
from pathlib import Path
|
||||
torch.manual_seed(1337)
|
||||
|
||||
#################################### Model #########################################
|
||||
|
||||
|
||||
# RoFormer: Enhanced Transformer with Rotary Position Embedding https://arxiv.org/abs/2104.09864
|
||||
class RoPE(nn.Module):
|
||||
def __init__(self, dim, max_seq_len=512):
|
||||
super().__init__()
|
||||
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
|
||||
t = torch.arange(max_seq_len).type_as(inv_freq)
|
||||
freqs = torch.einsum('i,j->ij', t, inv_freq)
|
||||
self.register_buffer('emb', torch.cat([freqs, freqs], dim=-1))
|
||||
|
||||
def rotate_half(self, x):
|
||||
x1, x2 = x.chunk(2, dim=-1)
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
def forward(self, x, offset=0):
|
||||
seq_len = x.size(1)
|
||||
emb = self.emb[offset:offset+seq_len].view(1, seq_len, -1)
|
||||
cos = emb.cos()
|
||||
sin = emb.sin()
|
||||
return (x * cos) + (self.rotate_half(x) * sin)
|
||||
|
||||
# Transformers without Normalization https://jiachenzhu.github.io/DyT/
|
||||
class DyT(nn.Module):
|
||||
def __init__(self, num_features, alpha_init_value=0.5):
|
||||
super().__init__()
|
||||
self.alpha = nn.Parameter(torch.ones(1) * alpha_init_value)
|
||||
self.weight = nn.Parameter(torch.ones(num_features))
|
||||
self.bias = nn.Parameter(torch.zeros(num_features))
|
||||
|
||||
def forward(self, x):
|
||||
x = torch.tanh(self.alpha * x)
|
||||
return x * self.weight + self.bias
|
||||
|
||||
# Attention Is All You Need https://arxiv.org/pdf/1706.03762v7
|
||||
# NeoBERT: A Next-Generation BERT https://arxiv.org/html/2502.19587v1
|
||||
class TransformerLayer(nn.Module):
|
||||
def __init__(self, h_dim, num_heads=4, dropout_rate = 0.1, max_seq_len = 128):
|
||||
super().__init__()
|
||||
self.__dict__.update({k:v for k,v in locals().items() if k != 'self'})
|
||||
self.q_proj = nn.Linear(h_dim, h_dim)
|
||||
self.k_proj = nn.Linear(h_dim, h_dim)
|
||||
self.v_proj = nn.Linear(h_dim, h_dim)
|
||||
self.o_proj = nn.Linear(h_dim, h_dim)
|
||||
self.ff1 = nn.Linear(h_dim, 4*h_dim)
|
||||
self.ff2 = nn.Linear(4*h_dim, h_dim)
|
||||
self.ln1 = DyT(h_dim)
|
||||
self.ln2 = DyT(h_dim)
|
||||
self.rope = RoPE(dim=h_dim//self.num_heads, max_seq_len=max_seq_len)
|
||||
|
||||
def split_to_heads(self, x, B, T, H):
|
||||
if self.num_heads <= 1: return x
|
||||
return rearrange(x, 'b t (n h) -> (b n) t h', b=B, t=T, n=self.num_heads)
|
||||
|
||||
def gather_heads(self, x, B, T, H):
|
||||
if self.num_heads <= 1: return x
|
||||
return rearrange(x, '(b n) t h -> b t (n h)', b=B, t=T, n=self.num_heads)
|
||||
|
||||
def attention(self, x):
|
||||
q = self.rope(self.split_to_heads(self.q_proj(x), *x.shape))
|
||||
k = self.rope(self.split_to_heads(self.k_proj(x), *x.shape))
|
||||
v = self.split_to_heads(self.v_proj(x), *x.shape)
|
||||
scores = (q @ k.transpose(1, 2)) * (self.h_dim ** -0.5)
|
||||
tril = torch.tril(torch.ones(x.shape[1],x.shape[1])).to(self.q_proj.bias.device)
|
||||
scores = scores.masked_fill(tril == 0, float('-inf')) # encoder does not need this line
|
||||
attention = nn.functional.softmax(scores, dim=2)
|
||||
return self.o_proj(self.gather_heads(attention @ v, *x.shape))
|
||||
|
||||
def forward(self, x):
|
||||
x = x + F.dropout1d(self.attention(self.ln1(x)), p=self.dropout_rate)
|
||||
x = x + F.dropout1d(self.ff2(F.gelu(self.ff1(self.ln2(x)))), p=self.dropout_rate)
|
||||
return x
|
||||
|
||||
class GPT2(nn.Module):
|
||||
def __init__(self, vocab_size, layers_num=1, h_dim=64, max_seq_len=128, num_heads=4, dropout_rate = 0.1, pixel_size=None):
|
||||
super().__init__()
|
||||
self.__dict__.update({k:v for k,v in locals().items() if k != 'self'})
|
||||
self.layers = nn.ModuleList([
|
||||
TransformerLayer(h_dim=self.h_dim, num_heads=self.num_heads, dropout_rate=self.dropout_rate, max_seq_len=self.max_seq_len)
|
||||
for _ in range(layers_num)])
|
||||
self.tok_embeds = nn.Embedding(vocab_size, h_dim)
|
||||
self.pos_embeds = nn.Parameter(torch.randn(1, self.max_seq_len, h_dim))
|
||||
self.lm_head = nn.Linear(h_dim, vocab_size)
|
||||
|
||||
def forward(self, x, targets=None):
|
||||
x = self.tok_embeds(x) + self.pos_embeds[:, :x.shape[1], :]
|
||||
for l in self.layers:
|
||||
x = l(x)
|
||||
logits = self.lm_head(x) # B,T,C
|
||||
loss = F.cross_entropy(rearrange(logits, "b t c -> b c t"), targets) if not targets is None else None
|
||||
return logits, loss
|
||||
|
||||
# what is the purpose? autoregressive inference!
|
||||
def generate(self, start_idx, max_new_tokens):
|
||||
idx = start_idx
|
||||
for i in range(max_new_tokens):
|
||||
idx_cond = idx[:,-self.max_seq_len:]
|
||||
logits, loss = self(idx_cond)
|
||||
logits = logits[:,-1,:] # B, C
|
||||
probs = F.softmax(logits, dim=-1)
|
||||
idx_next = torch.multinomial(probs, num_samples=1).to(self.lm_head.bias.device)
|
||||
idx = torch.cat([idx, idx_next], dim=1)
|
||||
return idx
|
||||
@ -0,0 +1,129 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.nn import functional as F
|
||||
from einops import rearrange
|
||||
import numpy as np
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
from datetime import datetime
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from char_gpt2 import GPT2
|
||||
from optics_char_gpt2 import OpticGPT2
|
||||
seed = 1337
|
||||
torch.manual_seed(seed)
|
||||
models = {'gpt2': GPT2, 'optic_gpt2': OpticGPT2}
|
||||
|
||||
batch_size = 50
|
||||
max_iters = 40000
|
||||
eval_interval = 300
|
||||
learning_rate = 1e-3
|
||||
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||
eval_iters = 200
|
||||
layers_num = 2
|
||||
h_dim = 64
|
||||
max_seq_len = 256
|
||||
num_heads = 1
|
||||
dropout_rate = 0.1
|
||||
pixel_size = 3.6e-6
|
||||
|
||||
# CUDA_VISIBLE_DEVICES=1 python .src/main.py gpt2|optic_gpt2 ./data/wiki.train.tokens ./data/wiki.valid.tokens ./data/wiki.test.tokens comment
|
||||
MODEL_CLASS = models[sys.argv[1]]
|
||||
train_data_path = Path(sys.argv[2])
|
||||
val_data_path = Path(sys.argv[3])
|
||||
test_data_path = Path(sys.argv[4])
|
||||
comment = f"{sys.argv[1]}_{train_data_path.name}_{sys.argv[5]}_{seed}"
|
||||
|
||||
logs_dir = f'logs/{datetime.now().date()}_{datetime.now().hour:02d}_{datetime.now().minute:02d}_{datetime.now().second:02d}_{comment}/'
|
||||
writer = SummaryWriter(logs_dir)
|
||||
script_snapshot_path = Path(logs_dir + Path(sys.argv[0]).name)
|
||||
print("Logs dir:", logs_dir)
|
||||
script_snapshot_path.write_bytes(Path(sys.argv[0]).read_bytes()) # copy this version of script
|
||||
script_snapshot_path.chmod(0o400) # with read-only permission
|
||||
#################################### Dataset #########################################
|
||||
|
||||
# wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
|
||||
with open(train_data_path, encoding='utf-8') as f:
|
||||
train_text = f.read()
|
||||
|
||||
with open(val_data_path, encoding='utf-8') as f:
|
||||
val_text = f.read()
|
||||
|
||||
with open(test_data_path, encoding='utf-8') as f:
|
||||
test_text = f.read()
|
||||
|
||||
text = train_text + val_text + test_text
|
||||
|
||||
chars = sorted(set(text))
|
||||
vocab_size = len(chars)
|
||||
|
||||
wtoi = {w:i for i,w in enumerate(chars)}
|
||||
itow = {i:w for i,w in enumerate(chars)}
|
||||
|
||||
encode = lambda s: [wtoi[w] for w in s]
|
||||
decode = lambda idx: ''.join([itow[i] for i in idx])
|
||||
|
||||
def get_batch(data, seq_len, batch_size):
|
||||
ix = torch.randint(len(data)-seq_len, (batch_size, ))
|
||||
x = torch.stack([data[i:i+seq_len] for i in ix]).to(device)
|
||||
y = torch.stack([data[i+1:i+1+seq_len] for i in ix]).to(device)
|
||||
return x, y
|
||||
|
||||
train_data = torch.tensor(encode(train_text), dtype=torch.long)
|
||||
val_data = torch.tensor(encode(val_text), dtype=torch.long)
|
||||
test_data = torch.tensor(encode(test_text), dtype=torch.long)
|
||||
|
||||
@torch.no_grad()
|
||||
def perplexity(model, data):
|
||||
stride = max(1, len(data) // 10000)
|
||||
losses = []
|
||||
for i in range(0, len(data)-max_seq_len-1, stride):
|
||||
x = data[i:(i+max_seq_len)].to(device)
|
||||
y = data[(i+1):(i+max_seq_len+1)].to(device)
|
||||
logits, loss = model(x[None,...], y[None,...])
|
||||
losses.append(loss.item())
|
||||
print(f"\rppl {i}/{len(data)-max_seq_len-1}", end="")
|
||||
return np.exp(np.mean(losses))
|
||||
|
||||
#################################### Model #########################################mo
|
||||
def complete(m, start_idxs=[0], max_new_tokens=100):
|
||||
start_idx = torch.tensor([start_idxs]).to(device)
|
||||
generated_tokens = m.generate(start_idx=start_idx, max_new_tokens=max_new_tokens)
|
||||
return decode(generated_tokens[0].tolist())
|
||||
|
||||
m = MODEL_CLASS(vocab_size=vocab_size, h_dim=h_dim, max_seq_len=max_seq_len, num_heads=num_heads, pixel_size=pixel_size)
|
||||
m = m.to(device)
|
||||
#################################### Train #########################################
|
||||
|
||||
optimizer = torch.optim.AdamW(m.parameters(), lr=learning_rate, betas=(0.90, 0.95), weight_decay=0.01)
|
||||
|
||||
completion = complete(m, encode("\n"*max_seq_len), 2*max_seq_len)
|
||||
print(completion)
|
||||
writer.add_text('completions', completion, 0)
|
||||
|
||||
for i in range(max_iters):
|
||||
xb, yb = get_batch(train_data, seq_len=max_seq_len, batch_size=batch_size)
|
||||
logits, loss = m(xb, yb)
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
writer.add_scalar('loss', loss.item(), i)
|
||||
print(f"\r{i}/{max_iters} {loss.item()}", end="")
|
||||
if i % 5000 == 0:
|
||||
ppl = perplexity(model=m, data=val_data)
|
||||
writer.add_scalar('val_perplexity', ppl.item(), i)
|
||||
print(f"\rPerplexity at {i}: {ppl}")
|
||||
writer.add_text('completions', complete(m, encode("\n"*max_seq_len), 2*max_seq_len), i)
|
||||
|
||||
ppl = perplexity(model=m, data=val_data)
|
||||
print(f"\r{i+1}/{max_iters} {loss.item()}")
|
||||
print(f"\rPerplexity at {i}: {ppl}")
|
||||
writer.add_scalar('val_perplexity', ppl.item(), i+1)
|
||||
writer.add_scalar('loss', loss.item(), i)
|
||||
|
||||
ppl = perplexity(model=m, data=test_data)
|
||||
writer.add_scalar('test_perplexity', ppl.item(), i+1)
|
||||
print(f"\rTest Perplexity at {i}: {ppl}")
|
||||
|
||||
completion = complete(m, encode("\n"*max_seq_len), 2*max_seq_len)
|
||||
print(completion)
|
||||
writer.add_text('completions', completion, i+1)
|
||||
@ -0,0 +1,9 @@
|
||||
__all__ = ["config",
|
||||
"propagator",
|
||||
"optical_mul"]
|
||||
__version__ = "3.0.0"
|
||||
|
||||
from .config import Config
|
||||
from . import propagator
|
||||
from .optical_mul import OpticalMul
|
||||
from .parallel import DataParallel
|
||||
@ -0,0 +1,177 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.nn import functional as F
|
||||
from einops import rearrange
|
||||
import optical_matrix_multiplication as omm
|
||||
from optical_matrix_multiplication import propagator
|
||||
import numpy as np
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
import sys
|
||||
torch.manual_seed(1337)
|
||||
|
||||
#################################### Model #########################################
|
||||
|
||||
def norm(matrix: torch.Tensor, max_val: float = 1) -> torch.Tensor:
|
||||
return matrix / (max_val + 1e-10)
|
||||
|
||||
def optics_matmul_shift(sim, tensor_1, tensor_2):
|
||||
tensor_1 = tensor_1[None,:,:,:]
|
||||
tensor_2 = tensor_2[None,:,:,:]
|
||||
|
||||
if torch.min(tensor_1) >= 0 and torch.min(tensor_2) >= 0:
|
||||
max_abs = abs(max(torch.max(tensor_1), torch.max(tensor_2)))
|
||||
a, b = norm(tensor_1, max_abs), norm(tensor_2, max_abs)
|
||||
return sim(a, b)[0,:,:,:] * max_abs **2
|
||||
|
||||
min_abs = abs(min(torch.min(tensor_1), torch.min(tensor_2)))
|
||||
max_abs = abs(max(torch.max(tensor_1), torch.max(tensor_2))) + min_abs
|
||||
|
||||
shift_a = min_abs * torch.ones(tensor_1.shape).to(tensor_1.device)
|
||||
shift_b = min_abs * torch.ones(tensor_2.shape).to(tensor_1.device)
|
||||
a_a_sh = tensor_1 + shift_a
|
||||
b_b_sh = tensor_2 + shift_b
|
||||
|
||||
a_a_sh_norm, b_b_sh_norm = norm(a_a_sh, max_abs), norm(b_b_sh, max_abs)
|
||||
shift_a_norm, shift_b_norm = norm(shift_a, max_abs), norm(shift_b, max_abs)
|
||||
a_a_sh_b_b_sh = sim(a_a_sh_norm, b_b_sh_norm)
|
||||
a_a_sh_b_sh = sim(a_a_sh_norm, shift_b_norm)
|
||||
a_sh_b_b_sh = sim(shift_a_norm, b_b_sh_norm)
|
||||
a_sh_b_sh = sim(shift_a_norm, shift_b_norm)
|
||||
|
||||
return (a_a_sh_b_b_sh - a_a_sh_b_sh - a_sh_b_b_sh + a_sh_b_sh)[0,:,:,:] * max_abs ** 2
|
||||
|
||||
# RoFormer: Enhanced Transformer with Rotary Position Embedding https://arxiv.org/abs/2104.09864
|
||||
class RoPE(nn.Module):
|
||||
def __init__(self, dim, max_seq_len=512):
|
||||
super().__init__()
|
||||
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
|
||||
t = torch.arange(max_seq_len).type_as(inv_freq)
|
||||
freqs = torch.einsum('i,j->ij', t, inv_freq)
|
||||
self.register_buffer('emb', torch.cat([freqs, freqs], dim=-1))
|
||||
|
||||
def rotate_half(self, x):
|
||||
x1, x2 = x.chunk(2, dim=-1)
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
def forward(self, x, offset=0):
|
||||
seq_len = x.size(1)
|
||||
emb = self.emb[offset:offset+seq_len].view(1, seq_len, -1)
|
||||
cos = emb.cos()
|
||||
sin = emb.sin()
|
||||
return (x * cos) + (self.rotate_half(x) * sin)
|
||||
|
||||
# Transformers without Normalization https://jiachenzhu.github.io/DyT/
|
||||
class DyT(nn.Module):
|
||||
def __init__(self, num_features, alpha_init_value=0.5):
|
||||
super().__init__()
|
||||
self.alpha = nn.Parameter(torch.ones(1) * alpha_init_value)
|
||||
self.weight = nn.Parameter(torch.ones(num_features))
|
||||
self.bias = nn.Parameter(torch.zeros(num_features))
|
||||
|
||||
def forward(self, x):
|
||||
x = torch.tanh(self.alpha * x)
|
||||
return x * self.weight + self.bias
|
||||
|
||||
# Attention Is All You Need https://arxiv.org/pdf/1706.03762v7
|
||||
# NeoBERT: A Next-Generation BERT https://arxiv.org/html/2502.19587v1
|
||||
class TransformerLayer(nn.Module):
|
||||
def __init__(self, h_dim, sim_scores, sim_output, num_heads=4, dropout_rate = 0.1, max_seq_len = 128):
|
||||
super().__init__()
|
||||
self.__dict__.update({k:v for k,v in locals().items() if k != 'self'})
|
||||
self.q_proj = nn.Linear(h_dim, h_dim)
|
||||
self.k_proj = nn.Linear(h_dim, h_dim)
|
||||
self.v_proj = nn.Linear(h_dim, h_dim)
|
||||
self.o_proj = nn.Linear(h_dim, h_dim)
|
||||
self.ff1 = nn.Linear(h_dim, 4*h_dim)
|
||||
self.ff2 = nn.Linear(4*h_dim, h_dim)
|
||||
self.ln1 = DyT(h_dim)
|
||||
self.ln2 = DyT(h_dim)
|
||||
self.rope = RoPE(dim=h_dim//self.num_heads, max_seq_len=max_seq_len)
|
||||
self.k1 = nn.Parameter(torch.randn(1))
|
||||
self.k2 = nn.Parameter(torch.randn(1))
|
||||
|
||||
def split_to_heads(self, x, B, T, H):
|
||||
if self.num_heads <= 1: return x
|
||||
return rearrange(x, 'b t (n h) -> (b n) t h', b=B, t=T, n=self.num_heads)
|
||||
|
||||
def gather_heads(self, x, B, T, H):
|
||||
if self.num_heads <= 1: return x
|
||||
return rearrange(x, '(b n) t h -> b t (n h)', b=B, t=T, n=self.num_heads)
|
||||
|
||||
def attention(self, x):
|
||||
q = self.rope(self.split_to_heads(self.q_proj(x), *x.shape))
|
||||
k = self.rope(self.split_to_heads(self.k_proj(x), *x.shape))
|
||||
v = self.split_to_heads(self.v_proj(x), *x.shape)
|
||||
scores = self.k1 * optics_matmul_shift(self.sim_scores, q, k.transpose(1, 2)) * (self.h_dim ** -0.5)
|
||||
tril = torch.tril(torch.ones(x.shape[1],x.shape[1])).to(self.q_proj.bias.device)
|
||||
scores = scores.masked_fill(tril == 0, float('-inf'))
|
||||
attention = nn.functional.softmax(scores, dim=2)
|
||||
output = self.k2 * optics_matmul_shift(self.sim_output, attention, v)
|
||||
return self.o_proj(self.gather_heads(output, *x.shape))
|
||||
|
||||
def forward(self, x):
|
||||
x = x + F.dropout1d(self.attention(self.ln1(x)), p=self.dropout_rate)
|
||||
x = x + F.dropout1d(self.ff2(F.gelu(self.ff1(self.ln2(x)))), p=self.dropout_rate)
|
||||
return x
|
||||
|
||||
class OpticGPT2(nn.Module):
|
||||
def __init__(self, vocab_size, layers_num=1, h_dim=64, max_seq_len=128, num_heads=4, dropout_rate = 0.1,
|
||||
pixel_size = 3.6e-6):
|
||||
super().__init__()
|
||||
self.__dict__.update({k:v for k,v in locals().items() if k != 'self'})
|
||||
self.sim_scores = omm.OpticalMul(
|
||||
omm.Config(right_matrix_count_columns = max_seq_len,
|
||||
right_matrix_count_rows = h_dim // num_heads,
|
||||
right_matrix_width = pixel_size * max_seq_len,
|
||||
right_matrix_height = pixel_size * (h_dim // num_heads),
|
||||
min_height_gap = pixel_size,
|
||||
right_matrix_split_x = 2,
|
||||
right_matrix_split_y = 2,
|
||||
left_matrix_split_x = 2,
|
||||
left_matrix_split_y = 2,
|
||||
result_matrix_split = 2,
|
||||
distance = 0.01)
|
||||
)
|
||||
|
||||
self.sim_output = omm.OpticalMul(
|
||||
omm.Config(right_matrix_count_columns = h_dim // num_heads,
|
||||
right_matrix_count_rows = max_seq_len,
|
||||
right_matrix_width = pixel_size * (h_dim // num_heads),
|
||||
right_matrix_height = pixel_size * max_seq_len,
|
||||
min_height_gap = pixel_size,
|
||||
right_matrix_split_x = 2,
|
||||
right_matrix_split_y = 2,
|
||||
left_matrix_split_x = 2,
|
||||
left_matrix_split_y = 2,
|
||||
result_matrix_split = 2,
|
||||
distance = 0.01)
|
||||
)
|
||||
self.layers = nn.ModuleList([
|
||||
TransformerLayer(h_dim=self.h_dim, sim_scores=self.sim_scores, sim_output=self.sim_output, num_heads=self.num_heads,
|
||||
dropout_rate=self.dropout_rate, max_seq_len=self.max_seq_len)
|
||||
for _ in range(layers_num)])
|
||||
self.tok_embeds = nn.Embedding(vocab_size, h_dim)
|
||||
self.pos_embeds = nn.Parameter(torch.randn(1, self.max_seq_len, h_dim))
|
||||
self.lm_head = nn.Linear(h_dim, vocab_size)
|
||||
|
||||
def forward(self, x, targets=None):
|
||||
x = self.tok_embeds(x) + self.pos_embeds[:, :x.shape[1], :]
|
||||
for l in self.layers:
|
||||
x = l(x)
|
||||
logits = self.lm_head(x) # B,T,C
|
||||
loss = F.cross_entropy(rearrange(logits, "b t c -> b c t"), targets) if not targets is None else None
|
||||
return logits, loss
|
||||
|
||||
# what is the purpose? autoregressive inference!
|
||||
def generate(self, start_idx, max_new_tokens):
|
||||
idx = start_idx
|
||||
for i in range(max_new_tokens):
|
||||
idx_cond = idx[:,-self.max_seq_len:]
|
||||
logits, loss = self(idx_cond)
|
||||
logits = logits[:,-1,:] # B, C
|
||||
probs = F.softmax(logits, dim=-1)
|
||||
idx_next = torch.multinomial(probs, num_samples=1).to(self.lm_head.bias.device)
|
||||
idx = torch.cat([idx, idx_next], dim=1)
|
||||
return idx
|
||||
Loading…
Reference in New Issue