midigpt 0.0.1b3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of midigpt might be problematic. Click here for more details.
- midigpt-0.0.1b3/LICENSE +21 -0
- midigpt-0.0.1b3/PKG-INFO +21 -0
- midigpt-0.0.1b3/README.md +5 -0
- midigpt-0.0.1b3/pyproject.toml +44 -0
- midigpt-0.0.1b3/setup.cfg +4 -0
- midigpt-0.0.1b3/setup.py +37 -0
- midigpt-0.0.1b3/src/midigpt/__init__.py +6 -0
- midigpt-0.0.1b3/src/midigpt/components.py +78 -0
- midigpt-0.0.1b3/src/midigpt/config.py +37 -0
- midigpt-0.0.1b3/src/midigpt/datasets/__init__.py +5 -0
- midigpt-0.0.1b3/src/midigpt/datasets/text_character.py +53 -0
- midigpt-0.0.1b3/src/midigpt/gpt.py +96 -0
- midigpt-0.0.1b3/src/midigpt/trainer.py +104 -0
- midigpt-0.0.1b3/src/midigpt/utils.py +13 -0
- midigpt-0.0.1b3/src/midigpt.egg-info/PKG-INFO +21 -0
- midigpt-0.0.1b3/src/midigpt.egg-info/SOURCES.txt +17 -0
- midigpt-0.0.1b3/src/midigpt.egg-info/dependency_links.txt +1 -0
- midigpt-0.0.1b3/src/midigpt.egg-info/requires.txt +4 -0
- midigpt-0.0.1b3/src/midigpt.egg-info/top_level.txt +1 -0
midigpt-0.0.1b3/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Johnny Greco
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
midigpt-0.0.1b3/PKG-INFO
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: midigpt
|
|
3
|
+
Version: 0.0.1b3
|
|
4
|
+
Summary: midiGPT: A MIDI Music Generation Library
|
|
5
|
+
Home-page: https://github.com/johnnygreco/midiGPT
|
|
6
|
+
Classifier: Intended Audience :: Science/Research
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Requires-Python: >=3.8
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
|
|
17
|
+
# 🎹 midiGPT
|
|
18
|
+
|
|
19
|
+
Inspired by Andrej Karpathy's [minGPT](https://github.com/karpathy/minGPT), I am building `midiGPT` as a learning-in-public (LIP) project. The goal is to build a library that makes it easy to train a decoder-only transformer model (similar to GPT) on MIDI data.
|
|
20
|
+
|
|
21
|
+
## 🚧 Under Construction 🚧
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# 🎹 midiGPT
|
|
2
|
+
|
|
3
|
+
Inspired by Andrej Karpathy's [minGPT](https://github.com/karpathy/minGPT), I am building `midiGPT` as a learning-in-public (LIP) project. The goal is to build a library that makes it easy to train a decoder-only transformer model (similar to GPT) on MIDI data.
|
|
4
|
+
|
|
5
|
+
## 🚧 Under Construction 🚧
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
[tool.black]
|
|
2
|
+
line-length = 120
|
|
3
|
+
|
|
4
|
+
[tool.ruff]
|
|
5
|
+
line-length = 120
|
|
6
|
+
|
|
7
|
+
# Enable Pyflakes `E` and `F` codes by default.
|
|
8
|
+
select = ["E", "F"]
|
|
9
|
+
ignore = ["F403", "F405"]
|
|
10
|
+
|
|
11
|
+
unfixable = ["F401", "F841"]
|
|
12
|
+
|
|
13
|
+
# Exclude a variety of commonly ignored directories.
|
|
14
|
+
exclude = [
|
|
15
|
+
".bzr",
|
|
16
|
+
".direnv",
|
|
17
|
+
".eggs",
|
|
18
|
+
".git",
|
|
19
|
+
".hg",
|
|
20
|
+
".mypy_cache",
|
|
21
|
+
".nox",
|
|
22
|
+
".pants.d",
|
|
23
|
+
".ruff_cache",
|
|
24
|
+
".svn",
|
|
25
|
+
".tox",
|
|
26
|
+
".venv",
|
|
27
|
+
"__pypackages__",
|
|
28
|
+
"_build",
|
|
29
|
+
"buck-out",
|
|
30
|
+
"build",
|
|
31
|
+
"dist",
|
|
32
|
+
"node_modules",
|
|
33
|
+
"venv",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[tool.ruff.per-file-ignores]
|
|
37
|
+
"__init__.py" = ["F401"]
|
|
38
|
+
|
|
39
|
+
[tool.ruff.isort]
|
|
40
|
+
known-first-party = ["midigpt"]
|
|
41
|
+
|
|
42
|
+
[tool.semantic_release]
|
|
43
|
+
branch = "main"
|
|
44
|
+
version_variable = "setup.py:__version__"
|
midigpt-0.0.1b3/setup.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from setuptools import find_packages, setup
|
|
4
|
+
|
|
5
|
+
if os.path.isfile("VERSION"):
|
|
6
|
+
with open("VERSION") as version:
|
|
7
|
+
__version__ = version.read().strip("v")
|
|
8
|
+
else:
|
|
9
|
+
__version__ = "0.0.1-beta.3"
|
|
10
|
+
|
|
11
|
+
with open("README.md", "r") as fh:
|
|
12
|
+
long_description = fh.read() or ""
|
|
13
|
+
|
|
14
|
+
with open("requirements.txt", "r") as f:
|
|
15
|
+
install_requires = f.read().splitlines()
|
|
16
|
+
|
|
17
|
+
setup(
|
|
18
|
+
name="midigpt",
|
|
19
|
+
version=__version__,
|
|
20
|
+
description="midiGPT: A MIDI Music Generation Library",
|
|
21
|
+
long_description=long_description,
|
|
22
|
+
packages=find_packages("src"),
|
|
23
|
+
package_dir={"": "src"},
|
|
24
|
+
python_requires=">=3.8",
|
|
25
|
+
install_requires=install_requires,
|
|
26
|
+
url="https://github.com/johnnygreco/midiGPT",
|
|
27
|
+
classifiers=[
|
|
28
|
+
"Intended Audience :: Science/Research",
|
|
29
|
+
"Programming Language :: Python :: 3",
|
|
30
|
+
"Programming Language :: Python :: 3.8",
|
|
31
|
+
"Programming Language :: Python :: 3.9",
|
|
32
|
+
"Programming Language :: Python :: 3.10",
|
|
33
|
+
"License :: OSI Approved :: MIT License",
|
|
34
|
+
"Topic :: Scientific/Engineering",
|
|
35
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
36
|
+
],
|
|
37
|
+
)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
import torch.nn as nn
|
|
5
|
+
from torch.nn import functional as F
|
|
6
|
+
|
|
7
|
+
from .config import ModelConfigure
|
|
8
|
+
|
|
9
|
+
__all__ = ["CasualMultiHeadAttention", "CasualAttentionBlock", "FeedForward"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GELU(nn.Module):
|
|
13
|
+
"""GELU activation function: https://arxiv.org/abs/1606.08415"""
|
|
14
|
+
|
|
15
|
+
def forward(self, x):
|
|
16
|
+
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CasualMultiHeadAttention(nn.Module):
|
|
20
|
+
def __init__(self, config: ModelConfigure) -> None:
|
|
21
|
+
super().__init__()
|
|
22
|
+
q_k_v_size = 3 * config.embedding_size
|
|
23
|
+
self.attn = nn.Linear(config.embedding_size, q_k_v_size)
|
|
24
|
+
self.output_projection = nn.Linear(config.embedding_size, config.embedding_size)
|
|
25
|
+
self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
|
|
26
|
+
self.embed_dropout = nn.Dropout(config.embed_dropout_prob)
|
|
27
|
+
_tril_reshape = torch.tril(torch.ones(config.context_length, config.context_length)).view(
|
|
28
|
+
1, 1, config.context_length, config.context_length
|
|
29
|
+
)
|
|
30
|
+
self.register_buffer("casual_mask", _tril_reshape)
|
|
31
|
+
self.num_heads = config.num_heads
|
|
32
|
+
self.embedding_size = config.embedding_size
|
|
33
|
+
|
|
34
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
35
|
+
d_batch, d_context, d_embed = x.size()
|
|
36
|
+
q, k, v = self.attn(x).split(self.embedding_size, dim=2)
|
|
37
|
+
q = q.view(d_batch, d_context, self.num_heads, d_embed // self.num_heads).transpose(1, 2)
|
|
38
|
+
k = k.view(d_batch, d_context, self.num_heads, d_embed // self.num_heads).transpose(1, 2)
|
|
39
|
+
v = v.view(d_batch, d_context, self.num_heads, d_embed // self.num_heads).transpose(1, 2)
|
|
40
|
+
|
|
41
|
+
attn = q @ k.transpose(-2, -1) / (k.size(-1) ** 0.5)
|
|
42
|
+
attn = attn.masked_fill(self.casual_mask[:, :, :d_context, :d_context] == 0, float("-inf"))
|
|
43
|
+
attn = F.softmax(attn, dim=-1)
|
|
44
|
+
attn = self.attn_dropout(attn)
|
|
45
|
+
attended_values = attn @ v
|
|
46
|
+
attended_values = attended_values.transpose(1, 2).contiguous().view(*x.size())
|
|
47
|
+
|
|
48
|
+
output = self.output_projection(attended_values)
|
|
49
|
+
output = self.embed_dropout(output)
|
|
50
|
+
return output
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class FeedForward(nn.Module):
|
|
54
|
+
def __init__(self, config: ModelConfigure) -> None:
|
|
55
|
+
super().__init__()
|
|
56
|
+
self.net = nn.Sequential(
|
|
57
|
+
nn.Linear(config.embedding_size, 4 * config.embedding_size),
|
|
58
|
+
GELU(),
|
|
59
|
+
nn.Linear(4 * config.embedding_size, config.embedding_size),
|
|
60
|
+
nn.Dropout(config.embed_dropout_prob),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def forward(self, x: torch.Tensor):
|
|
64
|
+
return self.net(x)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class CasualAttentionBlock(nn.Module):
|
|
68
|
+
def __init__(self, config: ModelConfigure):
|
|
69
|
+
super().__init__()
|
|
70
|
+
self.layer_norm_1 = nn.LayerNorm(config.embedding_size)
|
|
71
|
+
self.multi_head_self_attention = CasualMultiHeadAttention(config)
|
|
72
|
+
self.layer_norm_2 = nn.LayerNorm(config.embedding_size)
|
|
73
|
+
self.ff_net = FeedForward(config)
|
|
74
|
+
|
|
75
|
+
def forward(self, x: torch.Tensor):
|
|
76
|
+
x = x + self.multi_head_self_attention(self.layer_norm_1(x))
|
|
77
|
+
x = x + self.ff_net(self.layer_norm_2(x))
|
|
78
|
+
return x
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Optional, Union
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, root_validator
|
|
5
|
+
|
|
6
|
+
__all__ = ["ModelConfigure", "TrainConfigure"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ModelConfigure(BaseModel):
|
|
10
|
+
vocab_size: int
|
|
11
|
+
context_length: int = 64
|
|
12
|
+
embedding_size: int = 32
|
|
13
|
+
num_heads: int = 4
|
|
14
|
+
num_blocks: int = 4
|
|
15
|
+
attn_dropout_prob: float = 0.1
|
|
16
|
+
embed_dropout_prob: float = 0.1
|
|
17
|
+
device: str = "auto"
|
|
18
|
+
|
|
19
|
+
@root_validator
|
|
20
|
+
def check_embedding_size_num_heads_ratio(cls, values):
|
|
21
|
+
num_heads = values.get("num_heads")
|
|
22
|
+
embedding_size = values.get("embedding_size")
|
|
23
|
+
if embedding_size % num_heads != 0:
|
|
24
|
+
raise ValueError(f"{embedding_size=} is not divisible by {num_heads=}")
|
|
25
|
+
return values
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TrainConfigure(ModelConfigure):
|
|
29
|
+
batch_size: int = 32
|
|
30
|
+
learning_rate: float = 5e-4
|
|
31
|
+
eval_iters: int = 200
|
|
32
|
+
eval_interval: int = 500
|
|
33
|
+
num_epochs: int = 3
|
|
34
|
+
batches_per_epoch: Optional[int] = None
|
|
35
|
+
checkpoint_path: Union[str, Path] = Path("checkpoints")
|
|
36
|
+
save_all_checkpoints: bool = False
|
|
37
|
+
overwrite_checkpoints: bool = True
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import List, Union
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from torch.utils.data import Dataset
|
|
6
|
+
|
|
7
|
+
from ..config import ModelConfigure, TrainConfigure
|
|
8
|
+
|
|
9
|
+
__all__ = ["TextCharacterDataset", "TextCharacterTokenizer"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TextCharacterTokenizer:
|
|
13
|
+
def __init__(self, vocabulary: List[str]):
|
|
14
|
+
self.vocabulary = vocabulary
|
|
15
|
+
self.vocab_size = len(self.vocabulary)
|
|
16
|
+
self.str_to_int = {s: i for i, s in enumerate(self.vocabulary)}
|
|
17
|
+
self.int_to_str = {i: s for i, s in enumerate(self.vocabulary)}
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def from_corpus(cls, text_corpus: str):
|
|
21
|
+
vocabulary = sorted(set(text_corpus))
|
|
22
|
+
return cls(vocabulary)
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def from_file(cls, file_path: Union[str, Path]):
|
|
26
|
+
with open(file_path, "r") as f:
|
|
27
|
+
text_corpus = f.read()
|
|
28
|
+
return cls.from_corpus(text_corpus)
|
|
29
|
+
|
|
30
|
+
def encode(self, text: str):
|
|
31
|
+
return [self.str_to_int[s] for s in text]
|
|
32
|
+
|
|
33
|
+
def decode(self, tokens: List[int]):
|
|
34
|
+
return "".join([self.int_to_str[t] for t in tokens])
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class TextCharacterDataset(Dataset):
|
|
38
|
+
def __init__(self, text_corpus: str, vocabulary: List[str], config: Union[ModelConfigure, TrainConfigure]):
|
|
39
|
+
self.text_corpus = text_corpus
|
|
40
|
+
self.vocabulary = vocabulary
|
|
41
|
+
self.vocab_size = len(self.vocabulary)
|
|
42
|
+
self.context_length = config.context_length
|
|
43
|
+
self.tokenizer = TextCharacterTokenizer(vocabulary)
|
|
44
|
+
|
|
45
|
+
def __len__(self):
|
|
46
|
+
return len(self.text_corpus) - self.context_length
|
|
47
|
+
|
|
48
|
+
def __getitem__(self, idx):
|
|
49
|
+
context = self.text_corpus[idx : idx + self.context_length + 1]
|
|
50
|
+
context_encoded = self.tokenizer.encode(context)
|
|
51
|
+
x = torch.tensor(context_encoded[:-1], dtype=torch.long)
|
|
52
|
+
y = torch.tensor(context_encoded[1:], dtype=torch.long)
|
|
53
|
+
return x, y
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import List, Optional, Union
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
import torch.nn as nn
|
|
6
|
+
from torch.nn import functional as F
|
|
7
|
+
|
|
8
|
+
from . import utils
|
|
9
|
+
from .components import CasualAttentionBlock
|
|
10
|
+
from .config import ModelConfigure, TrainConfigure
|
|
11
|
+
|
|
12
|
+
__all__ = ["GPT"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GPT(nn.Module):
|
|
16
|
+
def __init__(self, config: Union[ModelConfigure, TrainConfigure]):
|
|
17
|
+
super().__init__()
|
|
18
|
+
self.token_embedding_table = nn.Embedding(config.vocab_size, config.embedding_size)
|
|
19
|
+
self.position_embedding_table = nn.Embedding(config.context_length, config.embedding_size)
|
|
20
|
+
self.blocks = nn.Sequential(*[CasualAttentionBlock(config) for _ in range(config.num_blocks)])
|
|
21
|
+
self.final_layer_norm = nn.LayerNorm(config.embedding_size)
|
|
22
|
+
self.reproject_to_vocab = nn.Linear(config.embedding_size, config.vocab_size)
|
|
23
|
+
self.apply(self._init_weights)
|
|
24
|
+
self.context_length = config.context_length
|
|
25
|
+
self.device = utils.get_auto_device() if config.device == "auto" else config.device
|
|
26
|
+
|
|
27
|
+
def _init_weights(self, module):
|
|
28
|
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
|
29
|
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
|
30
|
+
if hasattr(module, "bias") and module.bias is not None:
|
|
31
|
+
torch.nn.init.zeros_(module.bias)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def num_params(self):
|
|
35
|
+
return sum(p.numel() for p in self.parameters())
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def from_checkpoint(cls, path: Union[str, Path]):
|
|
39
|
+
checkpoint = torch.load(path)
|
|
40
|
+
config = checkpoint["model_config"]
|
|
41
|
+
model = cls(ModelConfigure(**config))
|
|
42
|
+
model.load_state_dict(checkpoint["model_state_dict"])
|
|
43
|
+
model.to(utils.get_auto_device() if config["device"] == "auto" else config["device"])
|
|
44
|
+
return model
|
|
45
|
+
|
|
46
|
+
def forward(self, x: torch.LongTensor, targets: Optional[torch.LongTensor] = None):
|
|
47
|
+
token_embedding = self.token_embedding_table(x) # (B, T, C)
|
|
48
|
+
position_embedding = self.position_embedding_table(torch.arange(x.shape[1], device=self.device)) # (T, C)
|
|
49
|
+
x = token_embedding + position_embedding # (B, T, C)
|
|
50
|
+
x = self.blocks(x) # (B, T, C)
|
|
51
|
+
x = self.final_layer_norm(x) # (B, T, C)
|
|
52
|
+
logits = self.reproject_to_vocab(x) # (B, T, vocab_size)
|
|
53
|
+
loss = (
|
|
54
|
+
None
|
|
55
|
+
if targets is None
|
|
56
|
+
else F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
|
57
|
+
)
|
|
58
|
+
return logits, loss
|
|
59
|
+
|
|
60
|
+
@torch.no_grad()
|
|
61
|
+
def generate(
|
|
62
|
+
self,
|
|
63
|
+
idx: Union[List[int], torch.LongTensor],
|
|
64
|
+
num_generated_tokens: int,
|
|
65
|
+
temperature: float = 1.0,
|
|
66
|
+
do_sample: bool = False,
|
|
67
|
+
top_k: Optional[int] = None,
|
|
68
|
+
as_list: bool = False,
|
|
69
|
+
):
|
|
70
|
+
idx = torch.as_tensor(idx, dtype=torch.long, device=self.device)[None, ...]
|
|
71
|
+
changed_training_mode = False
|
|
72
|
+
if self.training:
|
|
73
|
+
self.eval()
|
|
74
|
+
changed_training_mode = True
|
|
75
|
+
for _ in range(num_generated_tokens):
|
|
76
|
+
# if the sequence context is growing too long we must crop it at context_length
|
|
77
|
+
idx_cond = idx if idx.size(1) <= self.context_length else idx[:, -self.context_length :]
|
|
78
|
+
# forward the model to get the logits for the index in the sequence
|
|
79
|
+
logits, _ = self(idx_cond)
|
|
80
|
+
# pluck the logits at the final step and scale by desired temperature
|
|
81
|
+
logits = logits[:, -1, :] / temperature
|
|
82
|
+
# optionally crop the logits to only the top k options
|
|
83
|
+
if top_k is not None:
|
|
84
|
+
logits[logits < torch.topk(logits, top_k)[0][:, [-1]]] = -float("Inf")
|
|
85
|
+
# apply softmax to convert logits to (normalized) probabilities
|
|
86
|
+
probs = F.softmax(logits, dim=-1)
|
|
87
|
+
# either sample from the distribution or take the most likely element
|
|
88
|
+
idx_next = torch.multinomial(probs, num_samples=1) if do_sample else torch.topk(probs, k=1, dim=-1)[1]
|
|
89
|
+
# append sampled index to the running sequence and continue
|
|
90
|
+
idx = torch.cat((idx, idx_next), dim=1)
|
|
91
|
+
if changed_training_mode:
|
|
92
|
+
self.train()
|
|
93
|
+
return idx.cpu().squeeze().tolist() if as_list else idx
|
|
94
|
+
|
|
95
|
+
def save(self, path: Union[str, Path]):
|
|
96
|
+
torch.save(self.state_dict(), path)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
from torch.utils.data import DataLoader
|
|
7
|
+
from tqdm.rich import tqdm
|
|
8
|
+
from tqdm.std import TqdmExperimentalWarning
|
|
9
|
+
|
|
10
|
+
from . import utils
|
|
11
|
+
from .config import ModelConfigure, TrainConfigure
|
|
12
|
+
from .datasets import DatasetType
|
|
13
|
+
from .gpt import GPT
|
|
14
|
+
|
|
15
|
+
__all__ = ["Trainer"]
|
|
16
|
+
|
|
17
|
+
warnings.simplefilter("ignore", TqdmExperimentalWarning)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Trainer:
|
|
21
|
+
def __init__(self, config: TrainConfigure):
|
|
22
|
+
self.config = config
|
|
23
|
+
self.model = GPT(config)
|
|
24
|
+
self.checkpoint_path = Path(self.config.checkpoint_path)
|
|
25
|
+
self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=config.learning_rate)
|
|
26
|
+
self.device = utils.get_auto_device() if config.device == "auto" else config.device
|
|
27
|
+
self.model.to(self.device)
|
|
28
|
+
self._loss_history = []
|
|
29
|
+
|
|
30
|
+
def _save_loss_history(self):
|
|
31
|
+
with open(self.checkpoint_path / "loss_history.txt", "a") as f:
|
|
32
|
+
f.write("\n".join(map(str, self._loss_history)) + "\n")
|
|
33
|
+
self._loss_history = []
|
|
34
|
+
|
|
35
|
+
def _save_model_if_best(self, epoch: int, batch_num: int, loss: float, lowest_loss: float):
|
|
36
|
+
if loss < lowest_loss or self.config.save_all_checkpoints:
|
|
37
|
+
lowest_loss = loss
|
|
38
|
+
self.checkpoint_path.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
file_name = (
|
|
40
|
+
"best_model.ckpt" if self.config.overwrite_checkpoints else f"epoch_{epoch}_batch_{batch_num}.ckpt"
|
|
41
|
+
)
|
|
42
|
+
torch.save(
|
|
43
|
+
{
|
|
44
|
+
"epoch": epoch,
|
|
45
|
+
"batch_num": batch_num,
|
|
46
|
+
"loss": loss,
|
|
47
|
+
"train_config": self.config.dict(),
|
|
48
|
+
"model_config": {
|
|
49
|
+
k: v for k, v in self.config.dict().items() if k in ModelConfigure.__fields__.keys()
|
|
50
|
+
},
|
|
51
|
+
"model_state_dict": self.model.state_dict(),
|
|
52
|
+
"optimizer_state_dict": self.optimizer.state_dict(),
|
|
53
|
+
},
|
|
54
|
+
self.checkpoint_path / file_name,
|
|
55
|
+
)
|
|
56
|
+
return lowest_loss
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_checkpoint(cls, path: Union[str, Path]):
|
|
60
|
+
checkpoint = torch.load(path)
|
|
61
|
+
model_config = checkpoint["model_config"]
|
|
62
|
+
model = GPT(ModelConfigure(**model_config))
|
|
63
|
+
model.load_state_dict(checkpoint["model_state_dict"])
|
|
64
|
+
model.to(utils.get_auto_device() if model_config["device"] == "auto" else model_config["device"])
|
|
65
|
+
trainer = cls(TrainConfigure(**checkpoint["train_config"]))
|
|
66
|
+
trainer.model = model
|
|
67
|
+
trainer.loss = checkpoint["loss"]
|
|
68
|
+
trainer.optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
|
|
69
|
+
return trainer
|
|
70
|
+
|
|
71
|
+
def train(self, dataset: DatasetType, shuffle: bool = True):
|
|
72
|
+
self.train_loader = DataLoader(dataset=dataset, batch_size=self.config.batch_size, shuffle=shuffle)
|
|
73
|
+
batches_per_epoch = self.config.batches_per_epoch if self.config.batches_per_epoch else len(self.train_loader)
|
|
74
|
+
total_iterations = self.config.num_epochs * batches_per_epoch
|
|
75
|
+
with tqdm(total=total_iterations, desc=f"Training for {self.config.num_epochs} epochs:") as progress_bar:
|
|
76
|
+
lowest_loss = float("inf")
|
|
77
|
+
self.model.train()
|
|
78
|
+
for epoch in range(1, self.config.num_epochs + 1):
|
|
79
|
+
running_loss_epoch = 0.0
|
|
80
|
+
running_loss_batch_interval = 0.0
|
|
81
|
+
for batch_num, (x, y) in enumerate(self.train_loader, start=1):
|
|
82
|
+
x, y = x.to(self.device), y.to(self.device)
|
|
83
|
+
_, self.loss = self.model(x, y)
|
|
84
|
+
self.optimizer.zero_grad(set_to_none=True)
|
|
85
|
+
self.loss.backward()
|
|
86
|
+
self.optimizer.step()
|
|
87
|
+
running_loss_epoch += self.loss.item()
|
|
88
|
+
running_loss_batch_interval += self.loss.item()
|
|
89
|
+
self._loss_history.append(self.loss.item())
|
|
90
|
+
if batch_num % self.config.eval_interval == 0:
|
|
91
|
+
average_loss = running_loss_batch_interval / self.config.eval_interval
|
|
92
|
+
tqdm.write(
|
|
93
|
+
f"epoch: {epoch:<4.0f} | "
|
|
94
|
+
f"batch: {batch_num:<7.0f} | "
|
|
95
|
+
f"average batch loss: {average_loss:<.4f}"
|
|
96
|
+
)
|
|
97
|
+
lowest_loss = self._save_model_if_best(epoch, batch_num, average_loss, lowest_loss)
|
|
98
|
+
self._save_loss_history()
|
|
99
|
+
running_loss_batch_interval = 0.0
|
|
100
|
+
progress_bar.update(1)
|
|
101
|
+
if self.config.batches_per_epoch and batch_num > self.config.batches_per_epoch:
|
|
102
|
+
break
|
|
103
|
+
lowest_loss = self._save_model_if_best(epoch, batch_num, running_loss_epoch / batch_num, lowest_loss)
|
|
104
|
+
self._save_loss_history()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: midigpt
|
|
3
|
+
Version: 0.0.1b3
|
|
4
|
+
Summary: midiGPT: A MIDI Music Generation Library
|
|
5
|
+
Home-page: https://github.com/johnnygreco/midiGPT
|
|
6
|
+
Classifier: Intended Audience :: Science/Research
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Requires-Python: >=3.8
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
|
|
17
|
+
# 🎹 midiGPT
|
|
18
|
+
|
|
19
|
+
Inspired by Andrej Karpathy's [minGPT](https://github.com/karpathy/minGPT), I am building `midiGPT` as a learning-in-public (LIP) project. The goal is to build a library that makes it easy to train a decoder-only transformer model (similar to GPT) on MIDI data.
|
|
20
|
+
|
|
21
|
+
## 🚧 Under Construction 🚧
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
setup.py
|
|
5
|
+
src/midigpt/__init__.py
|
|
6
|
+
src/midigpt/components.py
|
|
7
|
+
src/midigpt/config.py
|
|
8
|
+
src/midigpt/gpt.py
|
|
9
|
+
src/midigpt/trainer.py
|
|
10
|
+
src/midigpt/utils.py
|
|
11
|
+
src/midigpt.egg-info/PKG-INFO
|
|
12
|
+
src/midigpt.egg-info/SOURCES.txt
|
|
13
|
+
src/midigpt.egg-info/dependency_links.txt
|
|
14
|
+
src/midigpt.egg-info/requires.txt
|
|
15
|
+
src/midigpt.egg-info/top_level.txt
|
|
16
|
+
src/midigpt/datasets/__init__.py
|
|
17
|
+
src/midigpt/datasets/text_character.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
midigpt
|