modelmakerlibrary 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,28 @@
1
+ def confirm_cpu_fallback(accelerator: str) -> None:
2
+ print(f"{accelerator} not available, using CPU.")
3
+ confirmation = input("Do you want to continue using CPU? (1 for Yes, 0 for No): ")
4
+ if confirmation != "1":
5
+ raise RuntimeError(f"{accelerator} is unavailable and CPU fallback was declined.")
6
+ print("Continuing with CPU.")
7
+
8
+
9
+ def init_accelerator(name: str, verbose: bool = False):
10
+ """Initialize an accelerator by name and return its torch device."""
11
+ from src.packages import torch
12
+
13
+ normalized_name = name.lower() if isinstance(name, str) else ""
14
+ if normalized_name == "cpu":
15
+ return torch.device("cpu")
16
+ if normalized_name in {"gpu", "cuda"}:
17
+ from .gpu import init_gpu
18
+
19
+ return init_gpu(verbose=verbose)
20
+ if normalized_name == "tpu":
21
+ from .tpu import init_tpu
22
+
23
+ return init_tpu(verbose=verbose)
24
+ if normalized_name == "npu":
25
+ from .npu import init_npu
26
+
27
+ return init_npu(verbose=verbose)
28
+ raise ValueError("Accelerator must be one of: cpu, gpu, tpu, npu.")
accelerator/gpu.py ADDED
@@ -0,0 +1,14 @@
1
+ from src.packages import torch
2
+ from . import confirm_cpu_fallback
3
+
4
+
5
+ def init_gpu(verbose: bool = False):
6
+ if torch.cuda.is_available():
7
+ device = torch.device("cuda")
8
+ if verbose:
9
+ print(f"GPU Memory Allocated: {torch.cuda.memory_allocated(device) / 1024 ** 2:.2f} MB")
10
+ print(f"Using GPU: {torch.cuda.get_device_name(device)}")
11
+ else:
12
+ confirm_cpu_fallback("GPU")
13
+ device = torch.device("cpu")
14
+ return device
accelerator/npu.py ADDED
@@ -0,0 +1,30 @@
1
+ import importlib
2
+
3
+ from src.packages import torch
4
+ from . import confirm_cpu_fallback
5
+
6
+
7
+ def init_npu(verbose: bool = False):
8
+ try:
9
+ importlib.import_module("torch_npu")
10
+ except ModuleNotFoundError as exc:
11
+ if exc.name != "torch_npu":
12
+ raise
13
+ confirm_cpu_fallback("NPU")
14
+ return torch.device("cpu")
15
+
16
+ npu_backend = getattr(torch, "npu", None)
17
+ is_available = getattr(npu_backend, "is_available", None)
18
+ if not callable(is_available):
19
+ raise RuntimeError("The installed torch-npu backend does not expose torch.npu.is_available().")
20
+ if not is_available():
21
+ confirm_cpu_fallback("NPU")
22
+ return torch.device("cpu")
23
+ device = torch.device("npu")
24
+ if verbose:
25
+ print(f"Using NPU: {device}")
26
+ return device
27
+
28
+
29
+ if __name__ == "__main__":
30
+ print(f"Using device: {init_npu(verbose=True)}")
accelerator/tpu.py ADDED
@@ -0,0 +1,24 @@
1
+ import importlib
2
+
3
+ from src.packages import torch
4
+ from . import confirm_cpu_fallback
5
+
6
+
7
+ def init_tpu(verbose: bool = False):
8
+ try:
9
+ torch_xla = importlib.import_module("torch_xla")
10
+ except ModuleNotFoundError as exc:
11
+ if exc.name != "torch_xla":
12
+ raise
13
+ confirm_cpu_fallback("TPU")
14
+ return torch.device("cpu")
15
+
16
+ runtime = importlib.import_module("torch_xla.runtime")
17
+ if runtime.device_type() != "TPU":
18
+ confirm_cpu_fallback("TPU")
19
+ return torch.device("cpu")
20
+
21
+ device = torch_xla.device()
22
+ if verbose:
23
+ print(f"Using TPU: {device}")
24
+ return device
modelMakerLibrary.py ADDED
@@ -0,0 +1,68 @@
1
+ """Public entry point for ModelMakerLibrary."""
2
+
3
+ from accelerator import init_accelerator
4
+ from accelerator.gpu import init_gpu
5
+ from accelerator.npu import init_npu
6
+ from accelerator.tpu import init_tpu
7
+ from src.dataset_function import (
8
+ data_loader,
9
+ dataset_convert,
10
+ init_dataset,
11
+ load_dataset,
12
+ split_dataset,
13
+ )
14
+ from src.NeuralNetwork_create import TextGenerationModel, init_nn, init_text_generator
15
+ from src.model import (
16
+ generate_text,
17
+ load_text_generator,
18
+ model_inference,
19
+ model_quantization,
20
+ model_save,
21
+ model_specs,
22
+ train_text_generator,
23
+ )
24
+ from src.tokenizers_function import init_tokenizer, tokenize_dataset
25
+
26
+ __all__ = [
27
+ "data_loader",
28
+ "dataset_convert",
29
+ "convert_dataset",
30
+ "init_accelerator",
31
+ "init_dataset",
32
+ "init_gpu",
33
+ "init_nn",
34
+ "init_npu",
35
+ "init_tokenizer",
36
+ "init_text_generator",
37
+ "init_tpu",
38
+ "load_dataset",
39
+ "model_inference",
40
+ "model_quantization",
41
+ "model_save",
42
+ "model_specs",
43
+ "split_dataset",
44
+ "TextGenerationModel",
45
+ "tokenize_dataset",
46
+ "tokenize_text_dataset",
47
+ "generate_text",
48
+ "load_text_generator",
49
+ "train_text_generator",
50
+ ]
51
+
52
+
53
+ def convert_dataset(dataset_path, output_path, format="json", model_type="text"):
54
+ """Convert a media-folder dataset to JSON, CSV, TSV, XML, or a supported table format."""
55
+ return dataset_convert(dataset_path, output_path, format, model_type)
56
+
57
+
58
+ def tokenize_text_dataset(
59
+ dataset_path,
60
+ output_path,
61
+ tokenizer_name="bert",
62
+ tokenizer_path=None,
63
+ max_length=512,
64
+ token=False,
65
+ ):
66
+ """Load a tokenizer by name and tokenize a text dataset in one call."""
67
+ tokenizer = init_tokenizer(tokenizer_name, tokenizer_path=tokenizer_path, token=token)
68
+ return tokenize_dataset(tokenizer, dataset_path, output_path, max_length=max_length)
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: modelmakerlibrary
3
+ Version: 0.1.0
4
+ Summary: Python tools for dataset preparation and neural-network experiments
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/IshaanShivalli/modelMakerLibrary
7
+ Project-URL: Repository, https://github.com/IshaanShivalli/modelMakerLibrary
8
+ Project-URL: Issues, https://github.com/IshaanShivalli/modelMakerLibrary/issues
9
+ Project-URL: Documentation, https://github.com/IshaanShivalli/modelMakerLibrary/tree/main/docs
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: torch
14
+ Requires-Dist: torchvision
15
+ Requires-Dist: numpy
16
+ Requires-Dist: transformers
17
+ Requires-Dist: tokenizers
18
+ Requires-Dist: pandas
19
+ Requires-Dist: matplotlib
20
+ Requires-Dist: safetensors
21
+ Requires-Dist: tsv
22
+ Dynamic: license-file
23
+
24
+ # ModelMakerLibrary
25
+
26
+ ModelMakerLibrary is a Python library for dataset preparation, neural-network
27
+ construction, and small byte-level text-generation experiments built on
28
+ PyTorch.
29
+
30
+ ## Install
31
+
32
+ ```shell
33
+ python -m pip install modelmakerlibrary
34
+ ```
35
+
36
+ The package installs its required runtime dependencies, including PyTorch,
37
+ Torchvision, Transformers, pandas, and Matplotlib. The standard PyTorch wheels
38
+ are suitable for CPU use; consult the official PyTorch installation selector
39
+ for GPU-specific builds. TPU support is optional and requires a compatible
40
+ PyTorch/XLA installation in a supported environment.
41
+
42
+ ## Quick start
43
+
44
+ ```python
45
+ import modelMakerLibrary as mml
46
+
47
+ dataset = mml.load_dataset("data/text", model_type="text")
48
+ train_set, test_set = mml.split_dataset(dataset, train_ratio=80)
49
+ train_batches = mml.data_loader(train_set, batch_size=8, shuffle=True)
50
+
51
+ result = mml.train_text_generator(
52
+ dataset_path="data/text",
53
+ output_path="output/text_generator.pt",
54
+ epochs=2,
55
+ device="cpu",
56
+ )
57
+ model = mml.load_text_generator(result["checkpoint_path"])
58
+ print(mml.generate_text(model, "A short prompt", max_new_tokens=40))
59
+ ```
60
+
61
+ For text generation, the input path can contain UTF-8 `.txt`, `.json`, `.csv`,
62
+ or `.tsv` files. JSON records use a `text` field; CSV and TSV files need a
63
+ `text` column. See [Dataset guide](docs/datasets.md) for directory layouts and
64
+ supported media types.
65
+
66
+ ## Documentation
67
+
68
+ - [Documentation index](docs/index.md)
69
+ - [Installation and compatibility](docs/installation.md)
70
+ - [Quickstart and examples](docs/quickstart.md)
71
+ - [Public API reference](docs/api.md)
72
+ - [Dataset loading and conversion](docs/datasets.md)
73
+ - [Models, training, and checkpoints](docs/models.md)
74
+ - [Accelerator setup](docs/accelerators.md)
75
+ - [Source module guide](docs/source-modules.md)
76
+ - [Development and testing](docs/development.md)
77
+ - [PyPI publishing and releases](docs/publishing.md)
78
+
79
+ The self-contained [Python example](examples/api_quickstart.py) creates its
80
+ own small dataset. The [Jupyter notebook](examples/modelmaker_quickstart.ipynb)
81
+ also includes local Jupyter, Google Colab, and Kaggle setup instructions.
82
+
83
+ ## License
84
+
85
+ This project is licensed under the Apache License 2.0. See [LICENSE](LICENSE)
86
+ for the full text.
@@ -0,0 +1,17 @@
1
+ modelMakerLibrary.py,sha256=DzDMs6JCn_2f99ATxm1Hme4B8MRYC8WSt4nvZVIC0U4,1844
2
+ accelerator/__init__.py,sha256=JsOGExJ2jAK3PZZVO2_uHOTOYWPwP1vcefVaxtD_Fs0,1058
3
+ accelerator/gpu.py,sha256=-3ZQoYp4waOZJaR9nhAybYTE8Obo3G4TMamvFGhUoWg,469
4
+ accelerator/npu.py,sha256=xtCPTEAiFetE1Y6eSBhwgOdIvbhpWiAM4vTU7OLWEA4,873
5
+ accelerator/tpu.py,sha256=w8_VPqgSiGay6pMHcijm5ZjcscgREAAm-e0qC6KK2BI,628
6
+ modelmakerlibrary-0.1.0.dist-info/licenses/LICENSE,sha256=ubvaiMx4bqvo0xoXzmlznRmaU8H41AbdblmJU_kNYjE,11362
7
+ src/NeuralNetwork_create.py,sha256=m1DJEA8I8XEU6JkDb1m-vxyEgQS7hbn9oo842UxgPx8,6940
8
+ src/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ src/dataset_function.py,sha256=n4my9G1z2HdB_RuJqvrFiQ-ow4t0NvXUSWvPSQuoBTM,29194
10
+ src/model.py,sha256=FX4GRjaPmzqCJqMdAdqMS8zU82kxocyR44qANQUAoNM,14191
11
+ src/packages.py,sha256=YjgzqhPYHjNDKWkwfe-w4J0S98Ams1V_n_j9hGEWySc,376
12
+ src/tokenizers_function.py,sha256=X9x781Dq-eCPA7_paitBuFnOn9OK_Els2lCPkSBlX1w,5598
13
+ src/train.py,sha256=6TItmqhOS3Dq_Bsd-SR3k9zliUey0waaEHGh5ysE5Ek,1090
14
+ modelmakerlibrary-0.1.0.dist-info/METADATA,sha256=Bjun2sy3Qlzybvuyr82awnazU46vdPiRXBBtIn1IryE,3058
15
+ modelmakerlibrary-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
16
+ modelmakerlibrary-0.1.0.dist-info/top_level.txt,sha256=KGQhd1Y6__g8BMiVA2p9W_G7iNDIQ-iuhEKleIwKibU,34
17
+ modelmakerlibrary-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition,
54
+ "submitted" means any form of electronic, verbal, or written
55
+ communication sent to the Licensor or its representatives, including
56
+ but not limited to communication on electronic mailing lists, source
57
+ code control systems, and issue tracking systems that are managed by,
58
+ or on behalf of, the Licensor for the purpose of discussing and
59
+ improving the Work, but excluding communication that is conspicuously
60
+ marked or otherwise designated in writing by the copyright owner as
61
+ "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ accelerator
2
+ modelMakerLibrary
3
+ src
@@ -0,0 +1,193 @@
1
+ from .packages import nn, torch
2
+
3
+
4
+ class TextGenerationModel(nn.Module):
5
+ """A byte-level causal Transformer configured by ModelMakerLibrary."""
6
+
7
+ def __init__(
8
+ self,
9
+ context_length: int = 64,
10
+ vocab_size: int = 256,
11
+ model_width: int = 52,
12
+ attention_heads: int = 4,
13
+ transformer_layers: int = 2,
14
+ ):
15
+ super().__init__()
16
+ if context_length <= 0 or vocab_size <= 0 or model_width <= 0:
17
+ raise ValueError("Context length, vocabulary size, and model width must be positive.")
18
+ if attention_heads <= 0 or model_width % attention_heads != 0:
19
+ raise ValueError("Model width must be divisible by the positive attention head count.")
20
+ if transformer_layers <= 0:
21
+ raise ValueError("Transformer layer count must be positive.")
22
+ self.context_length = context_length
23
+ self.vocab_size = vocab_size
24
+ self.model_width = model_width
25
+ self.attention_heads = attention_heads
26
+ self.transformer_layers = transformer_layers
27
+ self.token_embedding = nn.Embedding(vocab_size, model_width)
28
+ self.position_embedding = nn.Embedding(context_length, model_width)
29
+ encoder_layer = nn.TransformerEncoderLayer(
30
+ d_model=model_width,
31
+ nhead=attention_heads,
32
+ dim_feedforward=4 * model_width,
33
+ batch_first=True,
34
+ activation="gelu",
35
+ )
36
+ self.transformer = nn.TransformerEncoder(
37
+ encoder_layer,
38
+ num_layers=transformer_layers,
39
+ )
40
+ self.output_norm = nn.LayerNorm(model_width)
41
+ self.language_model_head = nn.Linear(model_width, vocab_size)
42
+
43
+ def forward(self, token_ids):
44
+ sequence_length = token_ids.size(1)
45
+ if sequence_length > self.context_length:
46
+ raise ValueError("Input sequence is longer than the model context.")
47
+ hidden = self.token_embedding(token_ids) + self.position_embedding(
48
+ torch.arange(sequence_length, device=token_ids.device)
49
+ )
50
+ causal_mask = torch.triu(
51
+ torch.ones(
52
+ sequence_length,
53
+ sequence_length,
54
+ dtype=torch.bool,
55
+ device=token_ids.device,
56
+ ),
57
+ diagonal=1,
58
+ )
59
+ hidden = self.transformer(hidden, mask=causal_mask)
60
+ return self.language_model_head(self.output_norm(hidden))
61
+
62
+
63
+ def init_text_generator(
64
+ context_length: int = 64,
65
+ vocab_size: int = 256,
66
+ model_width: int = 52,
67
+ attention_heads: int = 4,
68
+ transformer_layers: int = 2,
69
+ ) -> TextGenerationModel:
70
+ """Build a causal text-generation model with the library's Transformer layers."""
71
+ return TextGenerationModel(
72
+ context_length=context_length,
73
+ vocab_size=vocab_size,
74
+ model_width=model_width,
75
+ attention_heads=attention_heads,
76
+ transformer_layers=transformer_layers,
77
+ )
78
+
79
+
80
+ # Initializes a real torch neural network like FNN, CNNs, RNNs, LSTMs, GRUs, Transformers, GANs, Autoencoders, RBF, SOMs
81
+ def init_nn(nn_type: str, input_size: int, output_size: int, hidden_layers: int, batch_norm: bool, dropout: float, wt_decay: float):
82
+ if nn_type == "FNN":
83
+ layers = []
84
+ previous_size = input_size
85
+ hidden_size = input_size
86
+
87
+ for _ in range(hidden_layers):
88
+ layers.append(nn.Linear(previous_size, hidden_size))
89
+ if batch_norm:
90
+ layers.append(nn.BatchNorm1d(hidden_size))
91
+ layers.append(nn.ReLU())
92
+ if dropout > 0:
93
+ layers.append(nn.Dropout(dropout))
94
+ previous_size = hidden_size
95
+
96
+ layers.append(nn.Linear(previous_size, output_size))
97
+ return nn.Sequential(*layers)
98
+
99
+ if nn_type == "CNN":
100
+ layers = []
101
+ previous_channels = input_size
102
+ hidden_channels = input_size
103
+
104
+ for _ in range(hidden_layers):
105
+ layers.append(nn.Conv2d(previous_channels, hidden_channels, kernel_size=3, padding=1))
106
+ if batch_norm:
107
+ layers.append(nn.BatchNorm2d(hidden_channels))
108
+ layers.append(nn.ReLU())
109
+ if dropout > 0:
110
+ layers.append(nn.Dropout2d(dropout))
111
+ previous_channels = hidden_channels
112
+
113
+ layers.append(nn.Conv2d(previous_channels, output_size, kernel_size=3, padding=1))
114
+ return nn.Sequential(*layers)
115
+
116
+ if nn_type == "RNN":
117
+ layers = []
118
+ layers.append(nn.RNN(input_size, hidden_layers, batch_first=True))
119
+ return nn.Sequential(*layers)
120
+
121
+ if nn_type == "LSTM":
122
+ layers = []
123
+ layers.append(nn.LSTM(input_size, hidden_layers, batch_first=True))
124
+ return nn.Sequential(*layers)
125
+
126
+ if nn_type == "GRU":
127
+ layers = []
128
+ layers.append(nn.GRU(input_size, hidden_layers, batch_first=True))
129
+ return nn.Sequential(*layers)
130
+
131
+
132
+ if nn_type == "Transformer":
133
+ layers = []
134
+ layers.append(nn.Transformer(d_model=input_size, nhead=8, num_encoder_layers=hidden_layers, num_decoder_layers=hidden_layers))
135
+ return nn.Sequential(*layers)
136
+
137
+ if nn_type == "GAN":
138
+ # For GANs, we typically have a generator and a discriminator
139
+ generator = nn.Sequential(
140
+ nn.Linear(input_size, hidden_layers),
141
+ nn.ReLU(),
142
+ nn.Linear(hidden_layers, output_size),
143
+ nn.Tanh()
144
+ )
145
+ discriminator = nn.Sequential(
146
+ nn.Linear(output_size, hidden_layers),
147
+ nn.LeakyReLU(0.2),
148
+ nn.Linear(hidden_layers, 1),
149
+ nn.Sigmoid()
150
+ )
151
+ return generator, discriminator
152
+
153
+ if nn_type == "Autoencoder":
154
+ encoder = nn.Sequential(
155
+ nn.Linear(input_size, hidden_layers),
156
+ nn.ReLU(),
157
+ nn.Linear(hidden_layers, output_size)
158
+ )
159
+ decoder = nn.Sequential(
160
+ nn.Linear(output_size, hidden_layers),
161
+ nn.ReLU(),
162
+ nn.Linear(hidden_layers, input_size)
163
+ )
164
+ return encoder, decoder
165
+
166
+ if nn_type == "RBF":
167
+ # Radial Basis Function Network
168
+ layers = []
169
+ layers.append(nn.Linear(input_size, hidden_layers))
170
+ layers.append(nn.ReLU())
171
+ layers.append(nn.Linear(hidden_layers, output_size))
172
+ return nn.Sequential(*layers)
173
+
174
+
175
+ if nn_type == "SOM":
176
+ # Self-Organizing Map (SOM) is not a standard layer in PyTorch, so we will create a placeholder
177
+ class SOM(nn.Module):
178
+ def __init__(self, input_size, output_size):
179
+ super(SOM, self).__init__()
180
+ self.input_size = input_size
181
+ self.output_size = output_size
182
+ # Placeholder for SOM implementation
183
+
184
+ def forward(self, x):
185
+ # Placeholder for forward pass of SOM
186
+ return x # This should be replaced with actual SOM logic
187
+
188
+ return SOM(input_size, output_size)
189
+
190
+
191
+
192
+
193
+
src/__init__.py ADDED
File without changes