Skip to content

Commit 0696876

Browse files
simoninithomasWauplinosanseviero
authored
Integrating Hugging Face Hub 🤗 (updated) (#5856)
* Add Hugging Face Integration * Update setup.py * Update push_to_hf.py * Update push_to_hf.py * Update push_to_hf.py * Update push_to_hf.py Remove use_auth_token * Update push_to_hf.py * Update push_to_hf.py * Create Huggy * Update load_from_hf.py *Change loading to snapshot_download (able to use cache) * Update push_to_hf.py * Use create_repo and upload_folder instead of git * Apply suggestions from code review Co-authored-by: Lucain <[email protected]> Co-authored-by: Omar Sanseviero <[email protected]> * Delete Huggy + update load and push to hf * Delete Huggy config file * Update load_from_hf * Update push_to_hf * Apply suggestions from code review Co-authored-by: Omar Sanseviero <[email protected]> Co-authored-by: Lucain <[email protected]> * Update push_to_hf.py * Update with Omar Feedback * Black style formatter * Create __init__.py * Updates based on flake8 review * Change logging to MLAgents logger * Update python version * Update Python Version * Update setup.py * Update logger * Update logger * Pre-commit * Update Tuple * Update metadata generation * Ignore mypy error * Create Hugging-Face-Integration.md * Update ML-Agents-Toolkit-Documentation.md * Update style of Hugging-Face-Integration.md * Typo * Remove spaces --------- Co-authored-by: Lucain <[email protected]> Co-authored-by: Omar Sanseviero <[email protected]>
1 parent 9c27e73 commit 0696876

29 files changed

+351
-23
lines changed

DevProject/Assets/csc.rsp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
-warnaserror+
2-
-warnaserror-:618
2+
-warnaserror-:618

DevProject/DevProject.sln.DotSettings

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
2-
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RL/@EntryIndexedValue">RL</s:String></wpf:ResourceDictionary>
2+
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RL/@EntryIndexedValue">RL</s:String></wpf:ResourceDictionary>

DevProject/ProjectSettings/Packages/com.unity.testtools.codecoverage/Settings.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,4 @@
2020
}
2121
]
2222
}
23-
}
23+
}

Project/Assets/ML-Agents/Examples/PushBlockWithInput/PushBlockActions.inputactions

+1-1
Original file line numberDiff line numberDiff line change
@@ -176,4 +176,4 @@
176176
]
177177
}
178178
]
179-
}
179+
}

Project/Assets/ML-Agents/Examples/SharedAssets/Materials/ShaderOutline.shader

+1-1
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,4 @@ Shader "Custom/Outline and ScreenSpace texture"
8585
ENDCG
8686
}
8787
}
88-
}
88+
}

Project/Assets/ML-Agents/Examples/SharedAssets/Materials/ShaderRadialGrid.shader

+1-1
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,4 @@
8585
// ENDCG
8686
// }
8787
// }
88-
// }
88+
// }

Project/Project.sln.DotSettings

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
22
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ML/@EntryIndexedValue">ML</s:String>
3-
<s:Boolean x:Key="/Default/UserDictionary/Words/=Dont/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
3+
<s:Boolean x:Key="/Default/UserDictionary/Words/=Dont/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

com.unity.ml-agents.extensions/.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ build.bat.meta
1313

1414
# API Scraper output
1515
*.api
16-
*.api.meta
16+
*.api.meta

com.unity.ml-agents.extensions/Runtime/Input/Unity.ML-Agents.Extensions.Input.asmdef

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,4 @@
2020
}
2121
],
2222
"noEngineReferences": false
23-
}
23+
}

com.unity.ml-agents.extensions/Tests/Runtime/Input/Unity.ML-Agents.Extensions.Input.Tests.Runtime.asmdef

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,4 @@
2828
}
2929
],
3030
"noEngineReferences": false
31-
}
31+
}

com.unity.ml-agents/CODEOWNERS

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
# see https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners for more information
2-
* @unity/behavior-authoring
2+
* @unity/behavior-authoring

com.unity.ml-agents/Plugins/IL2CPP.DL.Stubs.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,4 @@ void * dlopen(const char *filename, int flags) {
77

88
void * dlsym(void *handle, const char *symbol) {
99
return 0;
10-
}
10+
}

com.unity.ml-agents/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ Please refer to the [ML-Agents documentation] page for usage guides.
1212

1313

1414
[ML-Agents github repo]: https://github.com/Unity-Technologies/ml-agents
15-
[ML-Agents documentation]: https://unity-technologies.github.io/ml-agents/
15+
[ML-Agents documentation]: https://unity-technologies.github.io/ml-agents/

com.unity.ml-agents/Runtime/Grpc/Unity.ML-Agents.CommunicatorObjects.asmdef

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@
1515
"defineConstraints": [],
1616
"versionDefines": [],
1717
"noEngineReferences": false
18-
}
18+
}

com.unity.ml-agents/Runtime/Unity.ML-Agents.asmdef

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,4 @@
3535
}
3636
],
3737
"noEngineReferences": false
38-
}
38+
}

com.unity.ml-agents/com.unity.ml-agents.sln.DotSettings

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,4 @@
1818
<s:Boolean x:Key="/Default/UserDictionary/Words/=Scriptable/@EntryIndexedValue">True</s:Boolean>
1919
<s:Boolean x:Key="/Default/UserDictionary/Words/=statsd/@EntryIndexedValue">True</s:Boolean>
2020
<s:Boolean x:Key="/Default/UserDictionary/Words/=stddev/@EntryIndexedValue">True</s:Boolean>
21-
<s:Boolean x:Key="/Default/UserDictionary/Words/=vals/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
21+
<s:Boolean x:Key="/Default/UserDictionary/Words/=vals/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

config/sac/FoodCollector.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,4 @@ behaviors:
2525
max_steps: 2000000
2626
time_horizon: 64
2727
summary_freq: 60000
28-
threaded: false
28+
threaded: false

docs/Hugging-Face-Integration.md

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# The Hugging Face Integration
2+
3+
The [Hugging Face Hub 🤗](https://huggingface.co/models?pipeline_tag=reinforcement-learning) is a central place **where anyone can share and download models**.
4+
5+
It allows you to:
6+
- **Host** your trained models.
7+
- **Download** trained models from the community.
8+
- Visualize your agents **playing directly on your browser**.
9+
10+
You can see the list of ml-agents models [here](https://huggingface.co/models?library=ml-agents).
11+
12+
We wrote a **complete tutorial to learn to train your first agent using ML-Agents and publish it to the Hub**:
13+
14+
- A short tutorial where you [teach **Huggy the Dog to fetch the stick** and then play with him directly in your browser](https://huggingface.co/learn/deep-rl-course/unitbonus1/introduction)
15+
- A [more in-depth tutorial](https://huggingface.co/learn/deep-rl-course/unit5/introduction)
16+
17+
## Download a model from the Hub
18+
19+
You can simply download a model from the Hub using `mlagents-load-from-hf`.
20+
21+
You need to define two parameters:
22+
23+
- `--repo-id`: the name of the Hugging Face repo you want to download.
24+
- `--local-dir`: the path to download the model.
25+
26+
For instance, I want to load the model with model-id "ThomasSimonini/MLAgents-Pyramids" and put it in the downloads directory:
27+
28+
```sh
29+
mlagents-load-from-hf --repo-id="ThomasSimonini/MLAgents-Pyramids" --local-dir="./downloads"
30+
```
31+
32+
## Upload a model to the Hub
33+
34+
You can simply upload a model to the Hub using `mlagents-push-to-hf`
35+
36+
You need to define four parameters:
37+
38+
- `--run-id`: the name of the training run id.
39+
- `--local-dir`: where the model was saved
40+
- `--repo-id`: the name of the Hugging Face repo you want to create or update. It’s always <your huggingface username>/<the repo name> If the repo does not exist it will be created automatically
41+
- `--commit-message`: since HF repos are git repositories you need to give a commit message.
42+
43+
For instance, I want to upload my model trained with run-id "SnowballTarget1" to the repo-id: ThomasSimonini/ppo-SnowballTarget:
44+
45+
```sh
46+
mlagents-push-to-hf --run-id="SnowballTarget1" --local-dir="./results/SnowballTarget1" --repo-id="ThomasSimonini/ppo-SnowballTarget" --commit-message="First Push"
47+
```
48+
49+
## Visualize an agent playing
50+
51+
You can watch your agent playing directly in your browser (if the environment is from the [ML-Agents official environments](Learning-Environment-Examples.md))
52+
53+
- Step 1: Go to https://huggingface.co/unity and select the environment demo.
54+
- Step 2: Find your model_id in the list.
55+
- Step 3: Select your .nn /.onnx file.
56+
- Step 4: Click on Watch the agent play

docs/ML-Agents-Toolkit-Documentation.md

+4
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@
3535
- [Creating Custom Side Channels](Custom-SideChannels.md)
3636
- [Creating Custom Samplers for Environment Parameter Randomization](Training-ML-Agents.md#defining-a-new-sampler-type)
3737

38+
## Hugging Face Integration
39+
40+
- [Using Hugging Face to download and upload trained models](Hugging-Face-Integration.md)
41+
3842
## Python Tutorial with Google Colab
3943

4044
- [Using a UnityEnvironment](https://colab.research.google.com/github/Unity-Technologies/ml-agents/blob/release_20_docs/colab/Colab_UnityEnvironment_1_Run.ipynb)

docs/Python-Custom-Trainer-Plugin.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,4 @@ mlagents-learn ml-agents-trainer-plugin/mlagents_trainer_plugin/a2c/a2c_3DBall.y
4848
## Tutorial
4949
Here’s a step-by-step [tutorial](Tutorial-Custom-Trainer-Plugin.md) on how to write a setup file and extend ml-agents trainers, optimizers, and
5050
hyperparameter settings.To extend ML-agents classes see references on
51-
[trainers](Python-On-Off-Policy-Trainer-Documentation.md) and [Optimizer](Python-Optimizer-Documentation.md).
51+
[trainers](Python-On-Off-Policy-Trainer-Documentation.md) and [Optimizer](Python-Optimizer-Documentation.md).

localized_docs/KR/docs/Training-Imitation-Learning.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,4 @@ without pre-recording a demonstration file. The steps to do this are as follows:
8282

8383
## 한글 번역
8484

85-
해당 문서의 한글 번역은 [민규식 (Kyushik Min)]([https://github.com/Kyushik](https://github.com/Kyushik))에 의해 진행되었습니다. 내용상 오류나 오탈자가 있는 경우 [email protected] 으로 연락주시면 감사드리겠습니다.
85+
해당 문서의 한글 번역은 [민규식 (Kyushik Min)]([https://github.com/Kyushik](https://github.com/Kyushik))에 의해 진행되었습니다. 내용상 오류나 오탈자가 있는 경우 [email protected] 으로 연락주시면 감사드리겠습니다.

localized_docs/KR/docs/Training-PPO.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -148,4 +148,4 @@ PPO는 에이전트의 관측 (Observation)을 통해 에이전트가 주어진
148148

149149
## 한글 번역
150150

151-
해당 문서의 한글 번역은 [민규식 (Kyushik Min)]([https://github.com/Kyushik](https://github.com/Kyushik))에 의해 진행되었습니다. 내용상 오류나 오탈자가 있는 경우 [email protected] 으로 연락주시면 감사드리겠습니다.
151+
해당 문서의 한글 번역은 [민규식 (Kyushik Min)]([https://github.com/Kyushik](https://github.com/Kyushik))에 의해 진행되었습니다. 내용상 오류나 오탈자가 있는 경우 [email protected] 으로 연락주시면 감사드리겠습니다.

localized_docs/TR/docs/Getting-Started.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -175,4 +175,4 @@ Eğitimli modeliniz `results/<run-identifier>/<behavior_name>.nn` konumunda olac
175175
[Example Environments](Learning-Environment-Examples.md) page.
176176
- For more information on the various training options available, check out the
177177
[Training ML-Agents](Training-ML-Agents.md) page.
178-
-->
178+
-->

ml-agents-envs/colabs/Colab_PettingZoo.ipynb

+1-1
Original file line numberDiff line numberDiff line change
@@ -315,4 +315,4 @@
315315
},
316316
"nbformat": 4,
317317
"nbformat_minor": 4
318-
}
318+
}

ml-agents/mlagents/utils/__init__.py

Whitespace-only changes.
+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import os
2+
import argparse
3+
4+
from huggingface_hub import snapshot_download
5+
6+
from mlagents_envs import logging_util
7+
from mlagents_envs.logging_util import get_logger
8+
9+
logger = get_logger(__name__)
10+
logging_util.set_log_level(logging_util.INFO)
11+
12+
13+
def load_from_hf(repo_id: str, local_dir: str) -> None:
14+
"""
15+
Download a model from Hugging Face Hub.
16+
:param repo_id: id of the model repository from the Hugging Face Hub
17+
:param local_dir: local destination of the repository
18+
"""
19+
_, repo_name = repo_id.split("/")
20+
21+
local_dir = os.path.join(local_dir, repo_name)
22+
23+
snapshot_download(repo_id=repo_id, local_dir=local_dir)
24+
25+
logger.info(f"The repository {repo_id} has been downloaded to {local_dir}")
26+
27+
28+
def main():
29+
parser = argparse.ArgumentParser()
30+
parser.add_argument(
31+
"--repo-id",
32+
help="Repo id of the model repository from the Hugging Face Hub",
33+
type=str,
34+
)
35+
parser.add_argument(
36+
"--local-dir",
37+
help="Local destination of the repository",
38+
type=str,
39+
default="./",
40+
)
41+
args = parser.parse_args()
42+
43+
# Load model from the Hub
44+
load_from_hf(args.repo_id, args.local_dir)
45+
46+
47+
# For python debugger to directly run this script
48+
if __name__ == "__main__":
49+
main()

0 commit comments

Comments
 (0)