torchfoundry 0.1.1__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.
File without changes
torchfoundry/data.py ADDED
@@ -0,0 +1,47 @@
1
+ from typing import Literal
2
+
3
+ from torch.utils.data import DataLoader
4
+
5
+ Selector=Literal["train","test"]
6
+
7
+ def loadDataset(selector:Selector| None=None, batch_size: int=64):
8
+ """
9
+ Get a FashionMNIST DataLoader.
10
+
11
+ Parameters
12
+ ----------
13
+ selector : {"train", "test"} or None, default=None
14
+ Select which dataset to return.
15
+ None returns both DataLoaders.
16
+
17
+ batch_size : int, default=64
18
+ Number of samples per batch (1-128).
19
+
20
+ Returns
21
+ -------
22
+ DataLoader or tuple[training_data, testing_data]
23
+ The selected DataLoader, or both DataLoaders.
24
+ """
25
+ if type(batch_size) is not int:
26
+ raise ValueError("batch_size must be an integer")
27
+ if not 0 < batch_size < 128:
28
+ raise ValueError("batch_size must be between 1 and 128")
29
+
30
+ trainData= "not finished"
31
+ testData="not finished"
32
+ raise ValueError("still in development")
33
+
34
+ if selector =="train":
35
+ training_data= DataLoader(trainData,batch_size=batch_size, shuffle=True)
36
+ return training_data
37
+ elif selector =="test":
38
+ testing_data= DataLoader(testData, batch_size=batch_size, shuffle=True)
39
+ return testing_data
40
+ elif selector is None:
41
+ training_data= DataLoader(trainData,batch_size=batch_size, shuffle=True)
42
+ testing_data= DataLoader(testData, batch_size=batch_size, shuffle=True)
43
+ return training_data, testing_data
44
+ else:
45
+ raise ValueError("selector must have value { test / train / None }")
46
+
47
+
torchfoundry/model.py ADDED
@@ -0,0 +1,93 @@
1
+ from pathlib import Path
2
+ from typing import Literal
3
+
4
+ import torch
5
+ from rich import print
6
+ from torch import nn
7
+ from torchinfo import summary
8
+
9
+ Summary=Literal[True,False]
10
+ def loadModel(layers,load_dict=None,Summary: bool=False, input_size=None):
11
+ """
12
+ Creates a PyTorch neural network and optionally loads pretrained weights
13
+ and displays a model summary.
14
+
15
+ Args:
16
+ layers (list[nn.Module]): PyTorch layers used to construct the model.
17
+ path (str | None): Path to a saved model state dictionary.
18
+ Summary (bool): Whether to display the model summary.
19
+ input_size (tuple | None): Dimensions of the model input, excluding
20
+ the batch dimension. Required if Summary is True.
21
+
22
+ Returns:
23
+ nn.Module: The constructed neural network.
24
+
25
+ Raises:
26
+ ValueError: If the path or input_size is invalid.
27
+ FileNotFoundError: If the checkpoint file does not exist.
28
+ """
29
+
30
+ #model device runtime
31
+ if torch.accelerator.is_available():
32
+ device=torch.accelerator.current_accelerator
33
+ else:
34
+ device='cpu'
35
+
36
+ class NeuralNetwork(nn.Module):
37
+ def __init__(self):
38
+ super().__init__()
39
+
40
+ self.layers=nn.Sequential(*layers)
41
+
42
+ def forward(self,x):
43
+ x=self.layers(x)
44
+ return x
45
+
46
+ model =NeuralNetwork().to(device)
47
+
48
+ #loading model
49
+ if load_dict is not None:
50
+
51
+ if not isinstance(load_dict, str):
52
+ raise ValueError("[red]path parameter must be string[/red]")
53
+ model_path= Path(load_dict)
54
+
55
+ if model_path.exists():
56
+ print("loading model..." ,flush=True)
57
+ model.load_state_dict(
58
+ torch.load(
59
+ model_path,
60
+ map_location=device,
61
+ weights_only=True
62
+ )
63
+ )
64
+
65
+ print("model created")
66
+ else:
67
+ print("[red]model path not found[/red]. Starting fresh")
68
+
69
+ #printing the model summary
70
+ if Summary:
71
+ if input_size is None:
72
+ raise ValueError("input_size canot be None when Summary is True")
73
+ summary(
74
+ model,
75
+ input_size=input_size,
76
+ col_names=["input_size","output_size","num_params","trainable"],
77
+ depth=1
78
+ )
79
+
80
+ return model
81
+
82
+ def saveModel(model,path):
83
+ if not model:
84
+ raise ValueError("model is a required parameter")
85
+ if not path:
86
+ raise ValueError("path is a required parameter")
87
+ if not isinstance(path, (str,Path)):
88
+ raise ValueError("path must be string or pathlib.Path")
89
+ if not isinstance(model, nn.Module):
90
+ raise ValueError("module must be a Pytorch nn.Module")
91
+
92
+ torch.save(model.state_dict(),path)
93
+ print(f"model saved at: {path} ")
@@ -0,0 +1,54 @@
1
+ import torch
2
+ from torch import nn
3
+ from torch.utils.data import DataLoader
4
+
5
+
6
+ def trainModel(model, dataloader, loss_fn, optimizer, epoch, save_dict=None ):
7
+
8
+ if not isinstance(model, nn.Module):
9
+ raise TypeError("module must be a Pytorch nn.Module")
10
+ if not isinstance(dataloader,DataLoader):
11
+ raise TypeError(
12
+ "dataloader must be an instance of torch.utils.data.DataLoader"
13
+ )
14
+ if not isinstance(epoch,int):
15
+ raise ValueError("epoch must be integer")
16
+ if not isinstance(save_dict, str):
17
+ raise ValueError("save_dict must be string")
18
+
19
+ if torch.accelerator.is_available():
20
+ device=torch.accelerator.current_accelerator
21
+ else:
22
+ device="cpu"
23
+
24
+ size=len(dataloader.dataset)
25
+
26
+ model.train()
27
+ for e in range(epoch):
28
+ print("")
29
+ print(f"epoch:{e+1}")
30
+ for batch, (x,y) in enumerate(dataloader):
31
+ x=x.to(device)
32
+ y=y.to(device)
33
+
34
+ pred=model(x)
35
+ loss=loss_fn(pred,y)
36
+
37
+ optimizer.zero_grad()
38
+ loss.backward()
39
+ optimizer.step()
40
+
41
+ if batch % 100==0:
42
+ loss=loss.item()
43
+ current=(batch+1)*len(x)
44
+
45
+ print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
46
+
47
+ if save_dict is not None:
48
+ try:
49
+ torch.save(model.state_dict(), save_dict)
50
+ print(f"model was saved at '{save_dict}'")
51
+ except (OSError, RuntimeError) as e:
52
+ raise RuntimeError(f"Failed to save model state_dict: {e}") from e
53
+
54
+
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: torchfoundry
3
+ Version: 0.1.1
4
+ Summary: Beginner-friendly utilities for building and training PyTorch models.
5
+ Author: Lorik Bajrami
6
+ License-Expression: MIT
7
+ Keywords: pytorch,machine-learning,deep-learning,training,data-science
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: torch
20
+ Requires-Dist: torchinfo
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest; extra == "dev"
23
+ Requires-Dist: ruff; extra == "dev"
24
+ Requires-Dist: build; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # ⚒️ TorchFoundry
28
+
29
+ **find your PyTorch workflow.**
30
+
31
+ TorchFoundry is a Python library designed to simplify and improve everyday workflows when working with PyTorch.
32
+ It aims to provide reusable utilities that reduce repetitive code and make machine learning development more convenient.
33
+ Make PyTorch development simpler, more reusable, and easier to maintain.
34
+
35
+ ### 🎓 Built for Learning
36
+ TorchFoundry was created with beginners in mind.
37
+
38
+ Especially those who want to get into the flow of training machine learning models without being overwhelmed by the complexity that can come with getting started.
39
+ The goal is to make the first steps into model development more approachable, allowing learners to focus on understanding the workflow and gradually build confidence in working with PyTorch.
40
+
41
+ However, simplification comes with trade-offs.
42
+ Abstracting away complexity can introduce limitations and hide implementation details that are important to understand. TorchFoundry is intended as a starting point, not a replacement for learning the underlying concepts. Anyone serious about exploring machine learning should investigate these limitations, understand what happens behind the abstractions, and learn when a more hands-on approach is necessary.
43
+
44
+ ### 🛠️ Built With
45
+
46
+ * Python
47
+ * PyTorch
48
+
49
+ ### 🚧 Project Status
50
+
51
+ TorchFoundry is currently under development. Features, functionality, and APIs are subject to change.
52
+
53
+ ### 📄 License
54
+
55
+ License information will be added as the project develops.
@@ -0,0 +1,9 @@
1
+ torchfoundry/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ torchfoundry/data.py,sha256=-t2sQul1_AVpnPcl22TXB8H5xzDvAZnQpY3_JC5TXFw,1544
3
+ torchfoundry/model.py,sha256=fYLjtlzZsWFJEVppKE-87AdGz1AWXBhBrl7ydKO_4qk,2877
4
+ torchfoundry/training.py,sha256=gOBsiBPc9tdm1SAP_nqcsZiACch9Anprr_kkxX7hP28,1633
5
+ torchfoundry-0.1.1.dist-info/licenses/LICENSE,sha256=GnX9_IwdaK49eje8WkbowdBE1E49IKUMw4EPQfBq8nw,1086
6
+ torchfoundry-0.1.1.dist-info/METADATA,sha256=LAIhgy7MpZT2zTdS2GeLL-_LXMI8stnHuMWrSI-1K30,2509
7
+ torchfoundry-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ torchfoundry-0.1.1.dist-info/top_level.txt,sha256=LvTk8ts_3Q9ZThECSWfs5tqgd-vgLL9hf-G0B-3oeQo,13
9
+ torchfoundry-0.1.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lorik440
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.
@@ -0,0 +1 @@
1
+ torchfoundry