Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bounty] PyTorch & HuggingFace Interface #139

Open
wants to merge 548 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 250 commits
Commits
Show all changes
548 commits
Select commit Hold shift + click to select a range
94de83f
removing broken llama.py
risingsunomi Aug 11, 2024
f63f4b0
Merge pull request #2 from exo-explore/main
risingsunomi Aug 11, 2024
ab273d3
Merge branch 'main' into main
risingsunomi Aug 22, 2024
c365749
Merge pull request #4 from exo-explore/main
risingsunomi Aug 24, 2024
0b8221f
Merge pull request #5 from exo-explore/main
risingsunomi Aug 24, 2024
226a0ac
removing unittest, update inference return type, fixing converting te…
risingsunomi Aug 25, 2024
e11bebd
adding nvidia quadro and t1000 support
risingsunomi Aug 25, 2024
778cb6e
updating test, updating model selection for smaller quant llama3 model
risingsunomi Aug 25, 2024
56aae50
added updating model options to update_deps.py
risingsunomi Aug 25, 2024
7df4640
updating inference class init to take shard, updating pytorch test_in…
risingsunomi Aug 25, 2024
aa769ca
adding updates for inference_engine.py
risingsunomi Aug 25, 2024
08e8b41
reducing layer amount for llama3-2b-base
risingsunomi Aug 25, 2024
dd2812b
fixing gpu tensor to numpy conversion issues, updating top_p_sampling…
risingsunomi Aug 25, 2024
7bcd35e
forward rewrite, adding in caching with dynamic cache, cache conversi…
risingsunomi Aug 26, 2024
3beea22
updates to caching, stuck on issue with infer_prompt and infer_tensor…
risingsunomi Aug 26, 2024
87a14ca
trying to fix infer problems
risingsunomi Aug 26, 2024
356bf2f
switched everything to use caching, did more prep for encoding the to…
risingsunomi Aug 26, 2024
aa89032
fixing test
risingsunomi Aug 26, 2024
b9331d7
adding init py for old python versions
risingsunomi Aug 26, 2024
2c7aa9c
update readme and add in init pys
risingsunomi Aug 26, 2024
6da3e94
adding more tests
risingsunomi Aug 26, 2024
d0bc93c
adding more try catch to move through tests
risingsunomi Aug 26, 2024
0e221b2
tests
risingsunomi Aug 26, 2024
9fc9fdb
added position embeddings, update test
risingsunomi Aug 26, 2024
2635b4c
tests
risingsunomi Aug 26, 2024
86e89eb
adding back tests
risingsunomi Aug 27, 2024
64fbacd
adding another test
risingsunomi Aug 27, 2024
fb7c73f
Merge pull request #6 from exo-explore/main
risingsunomi Aug 27, 2024
0d93130
added gc collect to remove gpu, fixed tokenizers warning
risingsunomi Aug 27, 2024
0ae716d
fixing device
risingsunomi Aug 27, 2024
7705639
adding smaller model test
risingsunomi Aug 27, 2024
81d597d
testing
risingsunomi Aug 28, 2024
f1d3e31
added tinyllama
risingsunomi Aug 28, 2024
bf0e606
changing top_p
risingsunomi Aug 28, 2024
432efb5
updating test
risingsunomi Aug 28, 2024
2cdc14c
adding A10, adding test
risingsunomi Aug 28, 2024
ed5bea7
removing reloading of shard, changing temp and top_p
risingsunomi Aug 28, 2024
ea41845
Merge pull request #7 from exo-explore/main
risingsunomi Aug 28, 2024
46667b6
Merge pull request #8 from risingsunomi/pr139-dev
risingsunomi Aug 28, 2024
032c9b1
rewrite of sharded model using new split testing of huggingface models
risingsunomi Sep 1, 2024
626b223
building out new hf.py class, testing qwen and llama3 8b
risingsunomi Sep 1, 2024
f983e93
trying to load in weights but transformers/pytorch doesnt allow that …
risingsunomi Sep 4, 2024
d142be0
adding more testing, refining logit selection
risingsunomi Sep 13, 2024
be8d7fb
working split model test, updating class
risingsunomi Sep 15, 2024
9d1ecdd
working on class and inference engine updates
risingsunomi Sep 15, 2024
4b0df06
building out inference engine test
risingsunomi Sep 15, 2024
623468c
adding working tests, update to forward function to just use input_id…
risingsunomi Sep 16, 2024
19b322d
cleaning up code and tests, debugging and adding in cleaned up loggin…
risingsunomi Sep 16, 2024
cc2c14c
getting infer and stop token issues
risingsunomi Sep 16, 2024
583629c
add tracking of next token and other logits into the full input_ids s…
risingsunomi Sep 17, 2024
7ec5bb8
grpc testing
risingsunomi Sep 17, 2024
5903e63
grpc testing
risingsunomi Sep 17, 2024
e7a3fd0
grpc testing
risingsunomi Sep 17, 2024
f6eec5a
grpc testing
risingsunomi Sep 17, 2024
d441a51
grpc testing
risingsunomi Sep 17, 2024
e7f6dcb
grpc testing
risingsunomi Sep 17, 2024
ba5b005
grpc testing
risingsunomi Sep 17, 2024
6242d76
grpc testing
risingsunomi Sep 17, 2024
5630731
grpc testing
risingsunomi Sep 17, 2024
4a29268
testing passing hidden states in inference_state
risingsunomi Sep 17, 2024
2daf65f
testing passing hidden states in inference_state
risingsunomi Sep 17, 2024
36d5cde
fixing scalar issue, reversing passing hidden_states
risingsunomi Sep 17, 2024
6917f30
inference bug fix, grpc testing
risingsunomi Sep 17, 2024
adab336
inference bug fix, grpc testing
risingsunomi Sep 17, 2024
73146dd
fixing hf model for hidden_states
risingsunomi Sep 17, 2024
929386d
fixing hf model for hidden_states
risingsunomi Sep 17, 2024
32b8f67
fixing hf model for hidden_states
risingsunomi Sep 17, 2024
c86facb
fixing hf model for hidden_states
risingsunomi Sep 17, 2024
d15b20d
fixing hf model for hidden_states
risingsunomi Sep 17, 2024
5e41bc4
fixing hf model for hidden_states
risingsunomi Sep 17, 2024
b29c5f8
fixing hf model for hidden_states
risingsunomi Sep 17, 2024
ddaa79c
fixing kvcache issue
risingsunomi Sep 17, 2024
3164d38
fixing kvcache issue
risingsunomi Sep 17, 2024
e8532bc
fixing kvcache issue
risingsunomi Sep 17, 2024
6a5b8db
fixing kvcache issue
risingsunomi Sep 17, 2024
515687d
working on passing past input_ids between infers and nodes
risingsunomi Sep 18, 2024
92ebdd5
implemented infer caching and passing cache information via inference…
risingsunomi Sep 19, 2024
f0795bd
removing dynamic cache passing in inference_state as model does its o…
risingsunomi Sep 19, 2024
b8f15a0
removed clearning cache on infer prompt and only on finished infer te…
risingsunomi Sep 19, 2024
d0f3cb7
hidden state dropping between nodes issue
risingsunomi Sep 19, 2024
fa6f263
hidden state dropping between nodes issue
risingsunomi Sep 19, 2024
2b0e7b5
hidden state dropping between nodes issue
risingsunomi Sep 19, 2024
f793c00
Merge branch 'main' of github.com:exo-explore/exo into exo-fork-update
risingsunomi Sep 19, 2024
131c158
Merge branch 'exo-fork-update' of github.com:risingsunomi/exo-nvidia …
risingsunomi Sep 19, 2024
43a1f61
Merge pull request #11 from risingsunomi/exo-fork-update
risingsunomi Sep 19, 2024
8398409
Merge branch 'exo-explore:main' into main
risingsunomi Sep 26, 2024
09572c1
Merge github.com:exo-explore/exo into exo-explore-main
risingsunomi Oct 2, 2024
c861f30
Merge pull request #13 from risingsunomi/exo-explore-main
risingsunomi Oct 2, 2024
cee3e31
cleaning up code, removing helpers.py
risingsunomi Oct 2, 2024
f95942f
Merge branch 'main' of github.com:risingsunomi/exo-nvidia
risingsunomi Oct 2, 2024
c3ea732
Merge branch 'main' into HEAD
AlexCheema Oct 6, 2024
57e14e8
adding needed libs to setup.py, fixing 4 space to 2 space issue, addi…
risingsunomi Oct 6, 2024
9fe3ec6
cleaning up code, added pytorch engine to llama 3.2 1b model shard in…
risingsunomi Oct 6, 2024
447da4a
Merge pull request #14 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 6, 2024
b44f6e9
updating pytorch requirement
risingsunomi Oct 6, 2024
6e1ab58
Merge pull request #15 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 6, 2024
936e60a
trying tokenizer fixes for llama3.1
risingsunomi Oct 6, 2024
43c3c62
detecting 3.1 for adding padding token and using autotokenizer for ll…
risingsunomi Oct 6, 2024
75a29f4
updating models.py to use instruct version
risingsunomi Oct 7, 2024
e407404
fixing autotokenizer
risingsunomi Oct 7, 2024
47ff4b3
Merge pull request #16 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 7, 2024
668668f
making it so position and cache is computed every forward on hf model
risingsunomi Oct 7, 2024
4e356f8
loading cached input_ids when passing hidden states
risingsunomi Oct 7, 2024
a5ef04a
loading cached iids from infer state fix
risingsunomi Oct 7, 2024
e888baa
device fix
risingsunomi Oct 7, 2024
7d9eb17
position id fix
risingsunomi Oct 7, 2024
1198628
fixing inference instance state issues between nodes
risingsunomi Oct 7, 2024
d25b7ac
node testing
risingsunomi Oct 7, 2024
0721a4c
node inference fix
risingsunomi Oct 7, 2024
49b682b
node inference fix
risingsunomi Oct 7, 2024
77a52a5
node inference fix
risingsunomi Oct 7, 2024
2b3397f
node inference fix
risingsunomi Oct 7, 2024
2e588af
node inference fix
risingsunomi Oct 7, 2024
e2eba05
node inference fix
risingsunomi Oct 7, 2024
d7699eb
node inference fix
risingsunomi Oct 7, 2024
bd9bf4f
inference between nodes fixed by always calculating position id and i…
risingsunomi Oct 7, 2024
72bed37
Merge pull request #17 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 7, 2024
913a008
cleaning up code
risingsunomi Oct 7, 2024
a1c1c76
Merge pull request #18 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 7, 2024
d509e43
Merge branch 'main' into HEAD
AlexCheema Oct 7, 2024
216e83d
Merge branch 'main' into HEAD
AlexCheema Oct 7, 2024
b518f73
comma and other text issue fix
risingsunomi Oct 7, 2024
296dff6
Merge pull request #19 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 7, 2024
9d24779
adding threadpooling to forward and logit sampling
risingsunomi Oct 9, 2024
fe6ae45
Merge pull request #20 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 9, 2024
2c55634
Merge branch 'exo-explore:main' into main
risingsunomi Oct 10, 2024
d4fb74f
rename (PyTorch, pytorch) -> (Torch, torch)
AlexCheema Oct 10, 2024
edf1c3d
add ci jobs for chatgpt_api_integration_test_torch_linux_cpu and chat…
AlexCheema Oct 10, 2024
0fd6711
add ci jobs for chatgpt_api_integration_test_torch_linux_cpu and chat…
AlexCheema Oct 10, 2024
a4feeab
ci filters
AlexCheema Oct 10, 2024
55fd482
rm comments
AlexCheema Oct 10, 2024
da39519
ci
AlexCheema Oct 10, 2024
89f1be0
Merge branch 'main' into HEAD
AlexCheema Oct 10, 2024
b6f6afc
Merge remote-tracking branch 'origin/main' into HEAD
AlexCheema Oct 10, 2024
5eb6c34
fixed torch device selection
risingsunomi Oct 11, 2024
ed64437
Merge branch 'main' of github.com:risingsunomi/exo-nvidia into pr139-…
risingsunomi Oct 11, 2024
18d41eb
fixing imports
risingsunomi Oct 11, 2024
c73ed76
Merge pull request #21 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 11, 2024
9ecbf0c
fixing chatgpt_api mistake
risingsunomi Oct 11, 2024
79c9e70
Merge branch 'exo-explore:main' into main
risingsunomi Oct 11, 2024
ebfd44a
Merge pull request #22 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 11, 2024
dae2cbe
removing old pytorch folder
risingsunomi Oct 11, 2024
1c1dd06
Merge pull request #23 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 11, 2024
55ae027
Update README.md
risingsunomi Oct 11, 2024
4b6a86d
set all torch models in models.py
AlexCheema Oct 11, 2024
830d33d
in torch, explicitly set the device when initilaizing the model
AlexCheema Oct 11, 2024
074dfe3
spacing
AlexCheema Oct 11, 2024
d9cfcc4
add model mlx-community/Qwen2-0.5B-Instruct-4bit
AlexCheema Oct 11, 2024
c3e1934
Merge branch 'exo-explore:main' into main
risingsunomi Oct 12, 2024
2c056b4
code changes from PR feedback, working on splitting of weights
risingsunomi Oct 12, 2024
da5c28d
Merge branch 'exo-explore:main' into pr139-dev-oct24
risingsunomi Oct 12, 2024
83a723b
doing more work toward individual safetensor loading, adding back dev…
risingsunomi Oct 13, 2024
47be250
working on split model, moving to server for more vram
risingsunomi Oct 13, 2024
ea0d4b1
change to hf downloader as was not getting all safetensor files
risingsunomi Oct 13, 2024
30b7991
splitting model still work in progress as transformers still seems to…
risingsunomi Oct 13, 2024
3a2c431
updating readme
risingsunomi Oct 13, 2024
4def538
Merge branch 'main' into pr139-dev-oct24
risingsunomi Oct 13, 2024
b35224c
Merge pull request #24 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 13, 2024
6c6e7b2
successful splitting model test with only loading needed weights, imp…
risingsunomi Oct 14, 2024
55ffdc7
Merge branch 'pr139-dev-oct24' of github.com:risingsunomi/exo-nvidia …
risingsunomi Oct 14, 2024
aacdeb5
adding model sharding to inference engine, doing testing with inferen…
risingsunomi Oct 14, 2024
ce702d1
fixing layer range issue
risingsunomi Oct 14, 2024
e387a79
fixing layer range issue
risingsunomi Oct 14, 2024
e0ba2bb
fixing layer range issue
risingsunomi Oct 14, 2024
5b9638f
checking if ram over usaage even if reducing layers on large models
risingsunomi Oct 14, 2024
664f29f
half layer inference engine testing
risingsunomi Oct 14, 2024
2591fab
fixing layer amount with sharded modeling
risingsunomi Oct 14, 2024
99dac57
adding qwen2.5 3B for testing
risingsunomi Oct 14, 2024
c12526f
Merge pull request #25 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 14, 2024
493cd3e
updating inference engine test
risingsunomi Oct 14, 2024
de23294
cleaning up utils and split model
risingsunomi Oct 14, 2024
d5a02be
Merge pull request #26 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 14, 2024
e7470b1
bugfix in llm setup
dtnewman Oct 15, 2024
fa24f46
Merge pull request #27 from dtnewman/main
risingsunomi Oct 15, 2024
5c69f3f
Merge remote-tracking branch 'origin/main' into HEAD
AlexCheema Oct 16, 2024
f5a1cef
handle range not satisfiable edge case
AlexCheema Oct 16, 2024
751bd1c
updating to use automodelforcausallm instead of autoconfig
risingsunomi Oct 16, 2024
7d866d8
removing meta model
risingsunomi Oct 16, 2024
253237b
updating split model test
risingsunomi Oct 16, 2024
e46ffa4
updating split model test
risingsunomi Oct 16, 2024
476b6ba
automodel fix
risingsunomi Oct 16, 2024
f7e02e9
fixing split model test
risingsunomi Oct 16, 2024
bd6322f
pytorch offload buffers error
risingsunomi Oct 17, 2024
c51bd91
device_map any issue with split model
risingsunomi Oct 17, 2024
4a2aef4
updating split model test
risingsunomi Oct 17, 2024
79f0763
fixing split model issue
risingsunomi Oct 17, 2024
cbbc9cf
fixing node issues
risingsunomi Oct 17, 2024
58cebab
fixing node issues
risingsunomi Oct 17, 2024
7f9b1bb
fixing node issues
risingsunomi Oct 17, 2024
c3adec5
fixing node issues
risingsunomi Oct 17, 2024
c8e6acc
fixing node issues
risingsunomi Oct 17, 2024
df028e2
fixing node issues, range issue
risingsunomi Oct 17, 2024
e5a1939
fixing node issues, range issue
risingsunomi Oct 17, 2024
d03a85c
Merge branch 'main' into pr139-dev-oct24
risingsunomi Oct 17, 2024
69a8955
Merge pull request #28 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 17, 2024
d07b825
adding num hidden layers manipulation for all models
risingsunomi Oct 18, 2024
a840e7f
updating to use shard_num_hidden_layers
risingsunomi Oct 18, 2024
bf5f22d
Merge branch 'main' of github.com:risingsunomi/exo-nvidia into pr139-…
risingsunomi Oct 18, 2024
52fa3f8
adding in better layer manipulation
risingsunomi Oct 18, 2024
ec49e31
adding in safe tensor sharding, generate model.safetensors.index.json…
risingsunomi Oct 19, 2024
f45b514
implementing sharding tests, fixing bugs with safetensor recompile
risingsunomi Oct 19, 2024
f90c24a
adding safetensor sharding, implementing it into model inference engine
risingsunomi Oct 20, 2024
696c264
updating backup and backup restore
risingsunomi Oct 20, 2024
9514e92
added removing backup when restoring
risingsunomi Oct 20, 2024
d65505e
added generating weight map if none, did updates to backup and restor…
risingsunomi Oct 20, 2024
d5b6113
cleaning up logging
risingsunomi Oct 20, 2024
d2302cc
updating docstring in newest class file
risingsunomi Oct 20, 2024
35c32eb
Merge pull request #29 from risingsunomi/pr139-dev-oct24
risingsunomi Oct 20, 2024
72fcf9b
starting write of llama3 model outside of transformers and using pytorch
risingsunomi Oct 21, 2024
9cac5ab
moving llama3 modeling source code, updating readme file
risingsunomi Oct 21, 2024
8012008
adding pytorch based llama model, added testing and working through bugs
risingsunomi Oct 23, 2024
291aa10
Merge branch 'exo-explore:main' into main
risingsunomi Oct 23, 2024
76323d7
Update llama3.py
risingsunomi Oct 23, 2024
0d66acd
updating pytorch llama model still, currently broken but backing up a…
risingsunomi Oct 23, 2024
fcb298b
Merge branch 'main' into main
AlexCheema Oct 23, 2024
1512d13
updated llamablock and llamamodel, created a MLP helper class to use …
risingsunomi Oct 25, 2024
0eb8044
fixing causual mask loading error, updated testing, working on logit …
risingsunomi Oct 25, 2024
a6768b4
adding a chat temple from tokenizer to test, looking at padding ids t…
risingsunomi Oct 25, 2024
8ba24e2
fixing parameter defintion on 4d mask method, commiting before trying…
risingsunomi Oct 26, 2024
6e32be6
merge fixing
risingsunomi Oct 27, 2024
df13fbc
Merge branch 'main' into pr/risingsunomi/30
risingsunomi Oct 27, 2024
6b3af3f
Merge branch 'main' of github.com:risingsunomi/exo-nvidia into pr139-…
risingsunomi Oct 27, 2024
cfb10ba
added in more base llm functions like multiheadattention and rotate e…
risingsunomi Oct 28, 2024
ea868c6
updating attentions, changed model struct, fixing kv cache
risingsunomi Oct 30, 2024
f1822e2
fixing kvcache for multiheadattention, fixing layers names for loadin…
risingsunomi Oct 30, 2024
38028c0
doing work with position_id and causal mask
risingsunomi Oct 31, 2024
0fd1797
updating torch readme with current model in development
risingsunomi Nov 1, 2024
5aaffe6
implemented using torchtune multiheadattention, added dot product att…
risingsunomi Nov 2, 2024
b2b63c3
FINALLY A WORKING PYTORCH ONLY MODEL, working on logit gen, shard tes…
risingsunomi Nov 3, 2024
f53ebd1
cleaning up custom dot product attention but might be removed, buildi…
risingsunomi Nov 3, 2024
e8db8ee
first layer run fixes, variable layer length weight loading fixes, wo…
risingsunomi Nov 10, 2024
22bc6a7
made it so weight for last output layer is only loaded when shard is …
risingsunomi Nov 11, 2024
7f2abc3
working on sharding issue where hidden state is not working when bein…
risingsunomi Nov 12, 2024
bdf3240
fixing last hidden value handling
risingsunomi Nov 15, 2024
227199f
update test
risingsunomi Nov 15, 2024
5af6302
update test
risingsunomi Nov 15, 2024
d7e5aca
update test
risingsunomi Nov 15, 2024
1874d23
update test, turn on caching
risingsunomi Nov 15, 2024
3a0ad62
test safetensor load
risingsunomi Nov 15, 2024
6098ae5
test hidden alignment
risingsunomi Nov 15, 2024
fa1e70f
updates to torchtune model, fixing non-generation errors, created spl…
risingsunomi Nov 17, 2024
d958bf9
split model working, updates to safetensor loading letting shard control
risingsunomi Nov 17, 2024
c8bdb09
reduced model loading ram by loading only some layers in layer list, …
risingsunomi Nov 17, 2024
75817eb
updating readme
risingsunomi Nov 17, 2024
73630d1
building out torch inference engine
risingsunomi Nov 18, 2024
ad99332
creating torch inference engine, separated torch and hf torch engines…
risingsunomi Nov 23, 2024
9ff2cc8
Merge github.com:exo-explore/exo into fork-merge
risingsunomi Nov 23, 2024
6ab6f1c
merge
risingsunomi Nov 23, 2024
811befc
Merge pull request #32 from risingsunomi/fork-merge
risingsunomi Nov 23, 2024
9f52f24
Merge branch 'exo-explore:main' into main
risingsunomi Nov 24, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion exo/api/chatgpt_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from exo.models import model_base_shards
from typing import Callable


class Message:
def __init__(self, role: str, content: Union[str, List[Dict[str, Union[str, Dict[str, str]]]]]):
self.role = role
Expand Down
1 change: 0 additions & 1 deletion exo/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ def get_system_info():
return "Linux"
return "Non-Mac, non-Linux system"


def find_available_port(host: str = "", min_port: int = 49152, max_port: int = 65535) -> int:
used_ports_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".exo_used_ports")

Expand Down
24 changes: 24 additions & 0 deletions exo/inference/pytorch/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Helper functions for pytorch inference
# Some code coming from tinygrad but written towards pytorch

import asyncio
import aiohttp
from tqdm import tqdm
from pathlib import Path
from typing import List

async def fetch_file_async(session, url: str, output_path: Path):
async with session.get(url) as response:
response.raise_for_status()
with open(output_path, 'wb') as f:
async for chunk in response.content.iter_chunked(8192):
f.write(chunk)

async def download_files(urls: List[str], output_paths: List[Path]):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This used?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I can remove

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove

Sorry forgot to. Will do that now.

async with aiohttp.ClientSession() as session:
tasks = []
for url, output_path in zip(urls, output_paths):
tasks.append(fetch_file_async(session, url, output_path))

for f in tqdm(asyncio.as_completed(tasks), total=len(tasks), desc="Downloading files"):
await f
137 changes: 137 additions & 0 deletions exo/inference/pytorch/inference.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# experimental, based off of tinygrad/inference.py

import numpy as np
import torch
import numpy as np
import json
from typing import Optional, Callable, Tuple
from exo.inference.shard import Shard
from exo.inference.inference_engine import InferenceEngine
from exo.inference.pytorch.model.hf import ShardedHuggingFaceModel
from exo.api.chatgpt_api import resolve_tokenizer
from exo.helpers import DEBUG
from transformers import DynamicCache

class PyTorchDynamicShardInferenceEngine(InferenceEngine):
"""
PyTorch Dynamic Shard Inference Engine for performing model inference with sharded models.
"""

def __init__(self):
"""
Initialize the inference engine.
Args:
debug (bool): If True, enables debug logging. Defaults to False.
"""
self.shard = None
self.model = None
self.tokenizer = None
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these the only options? I think supporting e.g. Mac with mps would be great since then you can run heterogeneous clusters.

One thing to try at some point would be mixing MLX and PyTorch and see if they are interoperable with exactly the same model.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With pytorch I don't think mac is fully rolled out yet. There seems to be some work arounds but CUDA and CPU are the only options on the pytorch download website. pytorch even stopped ROCm support for AMD

They have a nightly for testing MPS https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about this in the official "stable" docs: https://pytorch.org/docs/stable/notes/mps.html

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will try that but currently no mac to test. When I get through these other fixes though I can definitely add it for you or other mac users to test.


async def infer_prompt(
self,
request_id: str,
shard: Optional[Shard] = None,
prompt: str = "",
image_str: Optional[str] = None,
inference_state: Optional[str] = None
) -> Tuple[np.ndarray, str, bool]:
if DEBUG >= 2:
print("infer_prompt called")

await self.ensure_shard(shard)

# need to make this so inference_state is not a string
# cant use it with dynamic cache

tokens = self.tokenizer.encode(prompt, return_tensors="pt")

if DEBUG >= 2:
print(f"tokens: {tokens}\n")

output_data = self.model.forward_layers(
tokens
)

is_finished = output_data.size == 1 and output_data.item() in [self.tokenizer.eos_token_id]

if is_finished:
print(f"token from llm decode: {self.tokenizer.decode(output_data)}")


if DEBUG >= 2:
print(f"output_data: {output_data}\n")
print(f"output_data.size {output_data.size}\n")
print(f"output_data.item() {output_data.item()}")
print(f"finished: {is_finished}")
print(f"self.tokenizer.eos_token_id {self.tokenizer.eos_token_id}")
print(f"output_data[-1] {output_data[-1]}")
print(f"output_data.item() in [self.tokenizer.eos_token_id]: {output_data.item() in [self.tokenizer.eos_token_id]}")

return (
output_data,
"",
is_finished
)

async def infer_tensor(
self,
request_id: str,
shard: Shard,
input_data: np.ndarray,
inference_state: Optional[str] = None) -> Tuple[np.ndarray, str, bool]:

in_tensor = torch.tensor(input_data)

# Ensure input_data is 2D: [batch_size, seq_len]
if in_tensor.dim() == 1:
in_tensor = in_tensor.unsqueeze(0) # Add a batch dimension: [1, seq_len]

if DEBUG >= 2:
print("infer_tensor called")
print(f"input_data: {input_data}\n")
print(f"in_tensor: {in_tensor}\n")

await self.ensure_shard(shard)

output_data = self.model.forward_layers(
in_tensor
)

is_finished = output_data.size == 1 and output_data.item() in [self.tokenizer.eos_token_id]

if DEBUG >= 2:
print(f"output_data: {output_data}\n")
print(f"output_data.size {output_data.size}\n")
print(f"output_data.item() {output_data.item()}")
print(f"finished: {is_finished}")
print(f"self.tokenizer.eos_token_id {self.tokenizer.eos_token_id}")
print(f"output_data[-1] {output_data[-1]}")
print(f"output_data.item() in [self.tokenizer.eos_token_id]: {output_data.item() in [self.tokenizer.eos_token_id]}")

return (
output_data,
"",
is_finished
)

async def ensure_shard(self, shard: Optional[Shard]):
"""
Ensure the model shard is loaded and ready for inference.
Args:
shard (Optional[Shard]): Shard information for the model.
"""
if self.shard == shard:
return

if DEBUG >= 2:
print(f"Loading new shard: {shard}")

self.model = ShardedHuggingFaceModel(shard)
self.tokenizer = await resolve_tokenizer(shard.model_id)
self.shard = shard

if DEBUG >= 2:
print(f"Shard loaded successfully: {shard}")
107 changes: 107 additions & 0 deletions exo/inference/pytorch/model/hf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import torch
import torch.nn as nn
import numpy as np
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i dont think this is used


from transformers import AutoModelForCausalLM, LlamaConfig, DynamicCache, Cache
from exo.inference.shard import Shard
from exo.helpers import DEBUG
from typing import Tuple

from .utils import sample_logits

class ShardedHuggingFaceModel(torch.nn.Module):
def __init__(self, shard: Shard):
super(ShardedHuggingFaceModel, self).__init__()

if DEBUG >= 2:
print(f"\nShardedHuggingFaceModel init with shard {shard}")

self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.shard = shard



# Load the model
self.full_model = AutoModelForCausalLM.from_pretrained(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this download the entire model?
We have code to selectively download the model from HuggingFace so you don't have to download all layers on every device: exo/download

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also this won't work with our download progress code. We show in the TUI what the download progress of the model is.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this download the entire model? We have code to selectively download the model from HuggingFace so you don't have to download all layers on every device: exo/download

Will look at using that code because yes it currently does download all the model

shard.model_id,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, are these the only options? Would want support across other platforms

device_map="auto"
)

# using llamaconfig not working setting layers manually
layers = []
for i in range(shard.start_layer, shard.end_layer + 1):
layer = self.full_model.model.layers[i]

if DEBUG >= 2:
print(f"Loading layers[{i}]")

layers.append(layer)

self.full_model.model.layers = nn.ModuleList(layers)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does the peak memory usage look like here? I'm not sure of the specifics of python if this is going to hold each layer twice. Not sure but perhaps setting them in place would be more memory efficient.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They shouldn't be held twice as when the ensure_shard function is called in the infer_prompt or infer_tensor the init class function is called which loads the needed layers each time depending on the shard. Will make sure about memory limits though and usage.


if DEBUG >= 2:
print(f"full_model.model layer: {len(self.full_model.model.layers)}")

# Embeddings and final layer norm
# used for doing what forward LlamaModel does in transformers
self.embed_tokens = self.full_model.model.embed_tokens
self.norm = self.full_model.model.norm

# self.past_key_values = DynamicCache()

def forward_layers(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like this approach of generalising this so it works for other models without having to explicitly implement them.

Can you write a test for a model with a different architecture to make sure this generalises e.g. recurrent Gemma?
I wonder if we need a little bit of model-specific behaviour to enable this in general?

self,
input_data: torch.tensor
) -> Tuple[np.ndarray, list]:
"""
Forward pass through the specified layers.
Note: past_key_values not working for model, might be a library bug
"""
if DEBUG >= 2:
print("forward_layer call")
print(f"input_data: {input_data}")
print(f"shard {self.shard.to_dict()}")

hidden_states = input_data

# Forward pass through the layer
if DEBUG >= 2:
print(f"\n[layer model] {self.full_model.model}")
print(f"IN hidden_states {hidden_states}")
# print(f"past_kvs {past_kvs}")

self.full_model.model.layer_idx = 5
layer_outputs = self.full_model.model(
hidden_states,
# position_ids=position_ids,
# inputs_embeds=position_embeddings,
# past_key_values=self.past_key_values,
use_cache=False # not enough vram for using cache ;_;
)

if DEBUG >= 2:
print(f"OUT hidden_states {hidden_states}")
# print(f"\nlayer_outputs: {layer_outputs}")

hidden_states = layer_outputs.last_hidden_state
# self.past_key_values = layer_outputs.past_key_values

print(f"2 is_last_layer {self.shard.is_last_layer()}")
if self.shard.is_last_layer():
hs_norm = self.norm(hidden_states)
hs_lm_head = self.full_model.lm_head(hs_norm).float()

# Use the sampling function with default settings
output_token = sample_logits(
hs_lm_head[:, -1, :]).cpu().numpy().flatten()

if DEBUG >= 2:
print(f"hs_norm: {hs_norm}")
print(f"hs_lm_head: {hs_lm_head}")
print(f"output_token: {output_token}")

return output_token

return hidden_states.cpu().numpy()
63 changes: 63 additions & 0 deletions exo/inference/pytorch/model/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import torch
from torch.nn import functional as F

def sample_logits(logits, temperature=1.0, top_k=0, top_p=1.0, alpha_f=0.0, alpha_p=0.0):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be imported from somewhere rather than copy-pasta into the codebase? It looks like boilerplate code from somewhere.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I was testing it as the default values but will clean that part up. I will set it in the Interface class settings to be used.

"""
Sample tokens from logits using temperature, top-k, and top-p (nucleus) sampling.
Args:
logits (torch.Tensor): The logits distribution to sample from.
temperature (float): Temperature for scaling logits.
top_k (int): The number of top tokens to consider for sampling.
top_p (float): The cumulative probability threshold for nucleus sampling.
alpha_f (float): Penalty factor for repetition frequency.
alpha_p (float): Penalty for repeated selection.
Returns:
torch.Tensor: The selected token index.
"""

# Ensure logits are float
logits = logits.float()

# If temperature is very low, just use argmax
if temperature < 1e-6:
return logits.argmax(dim=-1)

# Alpha sampling (adjusting logits based on past selections)
if alpha_f > 0.0 or alpha_p > 0.0:
logits -= (sample_logits.alpha_counter * alpha_f + (sample_logits.alpha_counter > 0) * alpha_p)

# Replace NaNs with -inf to prevent softmax issues
logits = torch.where(torch.isnan(logits), torch.full_like(logits, -float('inf')), logits)

# Apply temperature scaling
logits = logits / temperature

# Top-k sampling
if top_k > 0:
top_k = min(top_k, logits.size(-1))
top_k_values, top_k_indices = torch.topk(logits, top_k, dim=-1)
logits = torch.full_like(logits, -float('inf'))
logits.scatter_(-1, top_k_indices, top_k_values)

# Top-p sampling
if 0 < top_p < 1.0:
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)

# Remove tokens with cumulative probability above the threshold
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0

sorted_logits[sorted_indices_to_remove] = -float('inf')
logits = sorted_logits

# Apply softmax to get probabilities
probabilities = F.softmax(logits, dim=-1)

# Sample from the probabilities
sampled_token = torch.multinomial(probabilities, 1)

return sampled_token.squeeze()
21 changes: 21 additions & 0 deletions exo/inference/pytorch/test_build_transformer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import unittest
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Run this test in circle ci ./.circleci/config.yml

from unittest.mock import patch, MagicMock
from pathlib import Path
import torch
from exo.inference.shard import Shard
from exo.inference.pytorch.helpers import build_transformer

class TestBuildTransformer(unittest.TestCase):

def test_build_transformer(self):
# Call the build_transformer function
model = build_transformer(
"gpt2",
quantize=True,
device="cuda"
)

self.assertIsNotNone(model)

if __name__ == '__main__':
unittest.main()
Loading