Skip to content

Commit

Permalink
first
Browse files Browse the repository at this point in the history
  • Loading branch information
wrongbad committed Jun 1, 2024
0 parents commit 421f97f
Show file tree
Hide file tree
Showing 14 changed files with 979 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.pt
*.egg-info
__pycache__
wip
9 changes: 9 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT LICENSE

Copyright 2024 Kyle Finn

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# torch2cpp

Status: WIP

Some features are supported, but most are not yet.

Models are traced with torch.fx to extract the flattened AST of low level function calls.

The AST graph is then traversed, generating C++ code in order.

Temporary buffer shapes and ref-counts are tracked to enable compile-time scheduled memory re-use (~10x buffer reduction in common cases).

Weights are stored in the binary as bfloat16, and unpacked to float32 at runtime. (Would like to investigate more options here for both storage and inference)

The bundled tensor math lib uses compile-time shapes and in-place storage, so there is no dynamic memory allocation at all.

16 changes: 16 additions & 0 deletions example/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
INCLUDES := $(shell python -m torch2cpp.includes)

build/model.js : build/model.cpp
em++ -Os build/model.cpp -I$(INCLUDES) \
-o build/model.js -s MODULARIZE=1 -s EXPORT_NAME=load_model \
-s EXPORTED_FUNCTIONS=_model_step,_model_reset,_model_encode,_model_decode

build/chat_cli : chat_cli.cpp build/model.cpp
c++ -std=c++17 -Os -march=native -ffast-math \
build/model.cpp chat_cli.cpp -I$(INCLUDES) -o build/chat_cli

.PHONY: model.js
model.js: build/model.js

.PHONY: chat_cli
chat_cli: build/chat_cli
2 changes: 2 additions & 0 deletions example/build/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!.gitignore
42 changes: 42 additions & 0 deletions example/chat_cli.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <string>
#include <iostream>

extern "C" {
void model_reset();
int model_step(int prevtok, float temperature);
int model_encode(char const* str, int str_len, int * out, int out_len);
int model_decode(int const* toks, int toks_len, char * out, int out_len);
} // extern C

int main(int argc, char ** argv)
{
std::string prompt;
constexpr int max_tokens = 256;
int toks[max_tokens];
char decode[max_tokens];
float temperature = 1;
while(true)
{
std::getline(std::cin, prompt);
prompt += "\n";

int n_tok = model_encode(prompt.c_str(), prompt.size(), toks, max_tokens);
for(int i=0 ; i<n_tok-1 ; i++)
{
model_step(toks[i], 0);
}
for(int i=n_tok-1 ; i<max_tokens ; i++)
{
toks[i+1] = model_step(toks[i], temperature);
int strlen = model_decode(toks+i+1, 1, decode, max_tokens);
std::cout << std::string(decode, strlen);
bool exit = false;
for(int j=0 ; j<strlen ; j++)
{
exit |= (decode[j]=='\n');
}
if(exit) { break; }
}
std::cout << std::endl;
}
}
107 changes: 107 additions & 0 deletions example/sqrll2cpp.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"params=11,698,432\n"
]
}
],
"source": [
"import torch\n",
"from sqrll.sqrllm import SqrLLM\n",
"\n",
"model_file = '../../sqrll/example/models/model2048bpe.pt'\n",
"\n",
"model = SqrLLM.load(model_file).eval()\n",
"\n",
"params = sum(p.numel() for p in model.parameters())\n",
"print(f'{params=:,}')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"n_vocab=2048\n"
]
}
],
"source": [
"from tokenizers import Tokenizer\n",
"\n",
"token_file = '../../sqrll/example/models/tokenizer2048.json'\n",
"\n",
"tokenizer = Tokenizer.from_file(token_file)\n",
"n_vocab = tokenizer.get_vocab_size()\n",
"print(f'{n_vocab=}')"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"from torch2cpp import codegen\n",
"from sqrll import sqrll, sqrllm\n",
"\n",
"inputs = torch.tensor([[0]])\n",
"_, mem = model(inputs)\n",
"mem = [torch.zeros_like(m) for m in mem]\n",
"\n",
"with open('build/model.cpp', 'w') as out_file:\n",
" codegen(\n",
" model,\n",
" out_file,\n",
" args=[inputs, mem],\n",
" tokenizer=tokenizer,\n",
" autowrap_functions=[\n",
" sqrll.sqrll_kernel,\n",
" sqrllm.rms_norm,\n",
" ],\n",
" skip_weights=False,\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[project]
name = "torch2cpp"
version = "0.0.1"

dependencies = [
"torch",
]
2 changes: 2 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import setuptools
setuptools.setup()
2 changes: 2 additions & 0 deletions src/torch2cpp/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

from .torch2cpp import codegen
Loading

0 comments on commit 421f97f

Please sign in to comment.