{"id":19156253,"url":"https://github.com/kyegomez/swarms-pytorch","last_synced_at":"2025-04-04T09:06:23.381Z","repository":{"id":197418923,"uuid":"698622866","full_name":"kyegomez/swarms-pytorch","owner":"kyegomez","description":"Swarming algorithms like PSO, Ant Colony, Sakana, and more in PyTorch 😊 ","archived":false,"fork":false,"pushed_at":"2025-01-27T23:48:02.000Z","size":61014,"stargazers_count":121,"open_issues_count":2,"forks_count":10,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-03-28T08:04:48.123Z","etag":null,"topics":["artificial-intelligence","firefly","gpt4","hivemind","machine-learning","multimodal","multimodal-deep-learning","multimodality","networks","neural-network","pso","swarm-algorithm","swarm-intelligence","swarm-optimization","swarm-robotics","swarms","swarms-of-agents"],"latest_commit_sha":null,"homepage":"https://swarmstorch.readthedocs.io/en/latest/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kyegomez.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["kyegomez"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"lfx_crowdfunding":null,"custom":null}},"created_at":"2023-09-30T13:19:50.000Z","updated_at":"2025-02-27T08:06:33.000Z","dependencies_parsed_at":"2023-12-20T11:59:27.461Z","dependency_job_id":"80048bad-519d-4439-8942-074afa299e75","html_url":"https://github.com/kyegomez/swarms-pytorch","commit_stats":null,"previous_names":["kyegomez/swarms-pytorch"],"tags_count":1,"template":false,"template_full_name":"kyegomez/Python-Package-Template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kyegomez%2Fswarms-pytorch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kyegomez%2Fswarms-pytorch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kyegomez%2Fswarms-pytorch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kyegomez%2Fswarms-pytorch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kyegomez","download_url":"https://codeload.github.com/kyegomez/swarms-pytorch/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247149500,"owners_count":20891954,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["artificial-intelligence","firefly","gpt4","hivemind","machine-learning","multimodal","multimodal-deep-learning","multimodality","networks","neural-network","pso","swarm-algorithm","swarm-intelligence","swarm-optimization","swarm-robotics","swarms","swarms-of-agents"],"created_at":"2024-11-09T08:33:52.152Z","updated_at":"2025-04-04T09:06:23.351Z","avatar_url":"https://github.com/kyegomez.png","language":"Python","funding_links":["https://github.com/sponsors/kyegomez","https://polar.sh/kyegomez"],"categories":[],"sub_categories":[],"readme":"[![Multi-Modality](agorabanner.png)](https://discord.gg/qUtxnK2NMf)\n\n# Novel Swarm Intelligence Model Architectures\n\n[![Join our Discord](https://img.shields.io/badge/Discord-Join%20our%20server-5865F2?style=for-the-badge\u0026logo=discord\u0026logoColor=white)](https://discord.gg/agora-999382051935506503) [![Subscribe on YouTube](https://img.shields.io/badge/YouTube-Subscribe-red?style=for-the-badge\u0026logo=youtube\u0026logoColor=white)](https://www.youtube.com/@kyegomez3242) [![Connect on LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=for-the-badge\u0026logo=linkedin\u0026logoColor=white)](https://www.linkedin.com/in/kye-g-38759a207/) [![Follow on X.com](https://img.shields.io/badge/X.com-Follow-1DA1F2?style=for-the-badge\u0026logo=x\u0026logoColor=white)](https://x.com/kyegomezb)\n\n\nSwarms in Torch exclusivley hosts a vast array of 100% novel swarming models. Our purpose for this repo is to create, optimize, and train novel foundation models that outperform the status quo of model architectures such as the Transformer and SSM model architectures. We provide implementations of various novel models like PSO with transformers as particles, ant colony with transformers as ants, a basic NN with transformers as neurons, Mixture of Mambas and many more. If you would like to help contribute to the future of AI model architecture's please join Agora, the open source lab here. And, if you have any idea's please submit them as issues and notify me.\n\n\n## Installation\n\n```bash\npip3 install swarms-torch\n```\n\n# Usage\n\n### ParticleSwarmOptimization\n\n```python\nfrom swarms_torch import ParticleSwarmOptimization\n\n\npso = ParticleSwarmOptimization(goal=\"Attention is all you need\", n_particles=100)\n\npso.optimize(iterations=1000)\n```\n\n### Ant Colony Optimization\n```python\nfrom swarms_torch.ant_colony_swarm import AntColonyOptimization\n\n# Usage:\ngoal_string = \"Hello ACO\"\naco = AntColonyOptimization(goal_string, num_iterations=1000)\nbest_solution = aco.optimize()\nprint(\"Best Matched String:\", best_solution)\n\n```\n\n### Neural Network with Transformers as synapases\n```python\nimport torch\nfrom swarms_torch.nnt import NNTransformer\n\nx = torch.randn(1, 10)\n\nnetwork = NNTransformer(\n    neuron_count = 5, \n    num_states = 10,\n    input_dim = 10,\n    output_dim = 10,\n    nhead = 2,\n)\noutput = network(x)\nprint(output)\n```\n\n### CellularSwarm\na Cellular Neural Net with transformers as cells, time simulation, and a local neighboorhood!\n\n```python\nfrom swarms_torch import CellularSwarm \n\nx = torch.randn(10, 32, 512)  # sequence length of 10, batch size of 32, embedding size of 512\nmodel = CellularSwarm(cell_count=5, input_dim=512, nhead=8)\noutput = model(x)\n\n```\n### Fish School/Sakana\n- An all-new innovative approaches to machine learning that leverage the power of the Transformer model architecture. These systems are designed to mimic the behavior of a school of fish, where each fish represents an individual Transformer model. The goal is to optimize the performance of the entire school by learning from the best-performing fish.\n\n```python\nimport torch\nfrom swarms_torch.fish_school import Fish, FishSchool\n\n# Create random source and target sequences\nsrc = torch.randn(10, 32, 512)\ntgt = torch.randn(10, 32, 512)\n\n# Create random labels\nlabels = torch.randint(0, 512, (10, 32))\n\n# Create a fish and train it on the random data\nfish = Fish(512, 8, 6)\nfish.train(src, tgt, labels)\nprint(fish.food)  # Print the fish's food\n\n# Create a fish school and optimize it on the random data\nschool = FishSchool(10, 512, 8, 6, 100)\nschool.forward(src, tgt, labels)\nprint(school.fish[0].food)  # Print the first fish's food\n\n```\n\n### Swarmalators\n```python\nfrom swarms_torch import visualize_swarmalators, simulate_swarmalators\n\n# Init for Swarmalator\n# Example usage:\nN = 100\nJ, alpha, beta, gamma, epsilon_a, epsilon_r, R = [0.1] * 7\nD = 3  # Ensure D is an integer\nxi, sigma_i = simulate_swarmalators(\n    N, J, alpha, beta, gamma, epsilon_a, epsilon_r, R, D\n)\n\n\n# Call the visualization function\nvisualize_swarmalators(xi)\n```\n\n### Mixture of Mambas\n- An 100% novel implementation of a swarm of MixtureOfMambas.\n- Various fusion methods through averages, weighted_aggegrate, and more to come like a gating mechanism or other various methods.\n- fusion methods: average, weighted, absmax, weighted_softmax, or your own custom function\n\n```python\nimport torch\nfrom swarms_torch import MixtureOfMambas\n\n# Create a 3D tensor for text\nx = torch.rand(1, 512, 512)\n\n# Create an instance of the MixtureOfMambas model\nmodel = MixtureOfMambas(\n    num_mambas=2,            # Number of Mambas in the model\n    dim=512,                 # Dimension of the input tensor\n    d_state=1024,            # Dimension of the hidden state\n    depth=4,                 # Number of layers in the model\n    d_conv=1024,             # Dimension of the convolutional layers\n    expand=4,                # Expansion factor for the model\n    fusion_method=\"absmax\",  # Fusion method for combining Mambas' outputs\n    custom_fusion_func=None  # Custom fusion function (if any)\n)\n\n# Pass the input tensor through the model and print the output shape\nprint(model(x).shape)\n\n```\n\n\n### `SwitchMoE`\n\n```python\nimport torch \nfrom swarms_torch import SwitchMoE\n\n# Example usage:\ninput_dim = 768  # Dimension of input tokens\nhidden_dim = 2048  # Hidden dimension of experts\noutput_dim = 768  # Output dimension, should match input dimension for residual connection\nnum_experts = 16  # Number of experts\n\nmoe_layer = SwitchMoE(\n    dim=input_dim,\n    hidden_dim=hidden_dim,\n    output_dim=output_dim,\n    num_experts=num_experts,\n    use_aux_loss=False,\n)\n\n# Create a sample input tensor (batch_size, seq_len, input_dim)\nx = torch.rand(32, 128, input_dim)\n\n# Forward pass through the MoE layer with auxiliary loss computation\noutput, auxiliary_loss = moe_layer(x)\n\n# Now, 'output' contains the MoE output, and 'auxiliary_loss' contains the load balancing loss.\n# This auxiliary loss should be added to the main loss function during training.\n\nprint(output)\nprint(auxiliary_loss)\n```\n### SimpleMoE\nA very simple Mixture of Experts with softmax as a gating mechanism.\n\n```python\nimport torch \nfrom swarms_torch import SimpleMoE\n\n# Example usage:\ninput_dim = 512  # Dimension of input tokens\nhidden_dim = 1024  # Hidden dimension of experts\noutput_dim = 512  # Output dimension, should match input dimension for residual connection\nnum_experts = 4  # Number of experts\n\nmoe = SimpleMoE(input_dim, hidden_dim, output_dim, num_experts)\n\n# Create a sample input tensor (batch_size, seq_len, input_dim)\nx = torch.rand(10, 16, input_dim)\n\n# Forward pass through the MoE layer\noutput = moe(x)\nprint(output)\n```\n\n### Firefly\n\nExploration into the Firefly algorithm (a generalized version of particle swarm optimization) in Pytorch. In particular interested in hybrid \u003ca href=\"https://academic.oup.com/jcde/article/9/2/706/6566441\"\u003efirefly + genetic algorithms\u003c/a\u003e, or ones that are \u003ca href=\"https://www.sciencedirect.com/science/article/abs/pii/S0957417423005298\"\u003egender-based\u003c/a\u003e. This code was adapted from lucidrains.\n\n```python\nfrom swarms_torch.firefly import FireflyOptimizer\nfrom torch import Tensor\n\n\ndef rosenbrock(x: Tensor) -\u003e Tensor:\n    return (\n        100 * (x[..., 1:] - x[..., :-1] ** 2) ** 2 + (1 - x[..., :-1]) ** 2\n    ).sum(dim=-1)\n\n\nif __name__ == \"__main__\":\n    optimizer = FireflyOptimizer(cost_function=rosenbrock)\n    optimizer.optimize()\n    best_solution = optimizer.get_best_solution()\n    print(f\"Best solution: {best_solution}\")\n\n```\n\n\n# Merging Multiple Models\n\n- `hyperslice_merge` Merge models by selecting specific slices of weight tensors across the models.\n\n- `random_subspace_merge` Merge models by randomly selecting subspaces of weights and averaging them.\n\n- `dimensional_cross_fusion` Merge models by fusing weights along a specific axis (dimension) across models.\n\n- `weighted_evolutionary_crossover` Merge models using a weighted crossover based on performance scores.\n\n- `permutation_weight_swapping` Merge models by permuting weight matrices and swapping them between models.\n\n\n```python\nimport torch \nfrom swarms_torch.mergers.all_new_evo_mergers import (\n    hyperslice_merge,\n    random_subspace_merge,\n    dimensional_cross_fusion,\n    weighted_evolutionary_crossover,\n    permutation_weight_swapping,\n)\n\n# Example of how to use the logger and merge methods\nif __name__ == \"__main__\":\n    # Example models, replace with actual model instances\n    model_1 = torch.nn.Linear(10, 10)\n    model_2 = torch.nn.Linear(10, 10)\n    model_3 = torch.nn.Linear(10, 10)\n\n    # Perform HyperSlice merge\n    merged_model_hs = hyperslice_merge(\n        [model_1, model_2, model_3], slice_indices=[0, 2, 4]\n    )\n\n    # Perform Random Subspace merge\n    merged_model_rs = random_subspace_merge(\n        [model_1, model_2, model_3], subspace_fraction=0.5\n    )\n\n    # Perform Dimensional Cross-fusion merge\n    merged_model_dc = dimensional_cross_fusion([model_1, model_2], cross_axis=0)\n\n    # Perform Weighted Evolutionary Crossover merge\n    merged_model_wc = weighted_evolutionary_crossover(\n        [model_1, model_2, model_3], performance_scores=[0.7, 0.85, 0.65]\n    )\n\n    # Perform Permutation-based Weight Swapping\n    merged_model_pw = permutation_weight_swapping(\n        [model_1, model_2], permutation_seed=42\n    )\n\n```\n\n\n\n\n# Documentation\n- [Click here for documentation](https://swarmstorch.readthedocs.io/en/latest/swarms/)\n\n# Examples\n- There are various scripts in the playground folder with various examples for each swarm, like ant colony and fish school and spiral optimization.\n\n\n## 🫶 Contributions:\n\nThe easiest way to contribute is to pick any issue with the `good first issue` tag 💪. Read the Contributing guidelines [here](/CONTRIBUTING.md). Bug Report? [File here](https://github.com/swarms/gateway/issues) | Feature Request? [File here](https://github.com/swarms/gateway/issues)\n\nSwarms is an open-source project, and contributions are VERY welcome. If you want to contribute, you can create new features, fix bugs, or improve the infrastructure. Please refer to the [CONTRIBUTING.md](https://github.com/kyegomez/swarms-pytorch/blob/master/CONTRIBUTING.md) and our [contributing board](https://github.com/users/kyegomez/projects/9) to participate in Roadmap discussions!\n\n\u003ca href=\"https://github.com/kyegomez/swarms-pytorch/graphs/contributors\"\u003e\n  \u003cimg src=\"https://contrib.rocks/image?repo=kyegomez/swarms-pytorch\" /\u003e\n\u003c/a\u003e\n\n----\n\n## Community\n\nJoin our growing community around the world, for real-time support, ideas, and discussions on Swarms 😊 \n\n- View our official [Blog](https://swarms.apac.ai)\n- Chat live with us on [Discord](https://discord.gg/kS3rwKs3ZC)\n- Follow us on [Twitter](https://twitter.com/kyegomez)\n- Connect with us on [LinkedIn](https://www.linkedin.com/company/the-swarm-corporation)\n- Visit us on [YouTube](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ)\n- [Join the Swarms community on Discord!](https://discord.gg/AJazBmhKnr)\n- Join our Swarms Community Gathering every Thursday at 1pm NYC Time to unlock the potential of autonomous agents in automating your daily tasks [Sign up here](https://lu.ma/5p2jnc2v)\n\n## Accelerate Backlog\nHelp us accelerate our backlog by supporting us financially! Note, we're an open source corporation and so all the revenue we generate is through donations at the moment ;)\n\n\u003ca href=\"https://polar.sh/kyegomez\"\u003e\u003cimg src=\"https://polar.sh/embed/fund-our-backlog.svg?org=kyegomez\" /\u003e\u003c/a\u003e\n\n# License\nMIT\n\n\n## Citations\n\n```bibtex\n@article{Yang2018WhyTF,\n    title   = {Why the Firefly Algorithm Works?},\n    author  = {Xin-She Yang and Xingshi He},\n    journal = {ArXiv},\n    year    = {2018},\n    volume  = {abs/1806.01632},\n    url     = {https://api.semanticscholar.org/CorpusID:46940737}\n}\n```\n\n```bibtex\n@article{article,\n    author  = {El-Shorbagy, M. and Elrefaey, Adel},\n    year    = {2022},\n    month   = {04},\n    pages   = {706-730},\n    title   = {A hybrid genetic-firefly algorithm for engineering design problems},\n    volume  = {Journal of Computational Design and Engineering, Volume 9},\n    journal = {Journal of Computational Design and Engineering},\n    doi     = {10.1093/jcde/qwac013}\n}\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkyegomez%2Fswarms-pytorch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkyegomez%2Fswarms-pytorch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkyegomez%2Fswarms-pytorch/lists"}