Additional code for Stable-baselines3 to load and upload models from the Hub.

Overview

Hugging Face x Stable-baselines3

A library to load and upload Stable-baselines3 models from the Hub.

Installation

With pip

Examples

[Todo: add colab tutorial]

Case 1: I want to download a model from the Hub

import gym

from huggingface_sb3 import load_from_hub
from stable_baselines3 import PPO

env = gym.make("CartPole-v1")

model = PPO("MlpPolicy", env, verbose=1)

# Retrieve the model from the hub
## repo_id =  id of the model repository from the Hugging Face Hub (repo_id = {organization}/{repo_name})
## filename = name of the model zip file from the repository
checkpoint = load_from_hub(repo_id="ThomasSimonini/ppo-CartPole-v1", filename="CartPole-v1")
PPO.load(checkpoint)

obs = env.reset()
for i in range(1000):
    action, _states = model.predict(obs, deterministic=True)
    obs, reward, done, info = env.step(action)
    env.render()
    if done:
      obs = env.reset()

env.close()

Case 2: I trained an agent and want to upload it to the Hub

First you need to be logged in to Hugging Face:

  • If you're using Colab/Jupyter Notebooks:
from huggingface_hub import notebook_login
notebook_login()
  • Else:
huggingface-cli login

Then:

import gym
from huggingface_sb3 import push_to_hub
from stable_baselines3 import PPO

# Create the environment
env = gym.make('CartPole-v1')

# Define a PPO MLpPolicy architecture
model = PPO('MlpPolicy', env, verbose=1)

# Train it for 10000 timesteps
model.learn(total_timesteps=10000)

# Save the model 
model.save("CartPole-v1")

# Push this saved model to the hf repo
# If this repo does not exists it will be created
## filename: the name of the file == "name" inside model.save("CartPole-v1")
push_to_hub(repo_name = "CartPole-v1",
           organization = "ThomasSimonini",  
           filename = "CartPole-v1", 
           commit_message = "Added Cartpole-v1 trained model")
Comments
  • Environment name normalization and explicit naming schemes

    Environment name normalization and explicit naming schemes

    There was an issue with environment names, that have a slash in their name (see https://github.com/DLR-RM/rl-baselines3-zoo/pull/257). Also the naming scheme for models and repository IDs is just based on convention.

    This PR implements normalization for environment names (replacing slashes with dashes) and encodes the naming scheme for models and repository IDs in little helper classes. The idea is, that those helper classes can be used by downstream libraries to comply with the naming scheme (such as the rl baselines zoo). If we ever need to change the naming scheme or other cases in which the environment name needs to be normalized come up, then we can implement them here and the downstream libraries immediately profit from that.

    I also added a simple smoke test for pulling a model from the hub.

    opened by ernestum 8
  • 400 Client Error for `package_to_hub` function

    400 Client Error for `package_to_hub` function

    I am going through the notebook of Unit 1 of the deep RL course. However, I cannot run the package_to_hub function, which gives the following error:

    HTTPError                                 Traceback (most recent call last)
    
    [<ipython-input-26-97f48e41190b>](https://localhost:8080/#) in <module>
         25                eval_env=eval_env,
         26                repo_id="LorenzoPacchiardi/ppo-LunarLander-v2",
    ---> 27                commit_message="Upload PPO LunarLander-v2 trained agent (50 steps)")
    
    6 frames
    
    [/usr/local/lib/python3.7/dist-packages/requests/models.py](https://localhost:8080/#) in raise_for_status(self)
        939 
        940         if http_error_msg:
    --> 941             raise HTTPError(http_error_msg, response=self)
        942 
        943     def close(self):
    
    HTTPError: 400 Client Error: Bad Request for url: https://huggingface.co/api/models/LorenzoPacchiardi/ppo-LunarLander-v2/commit/main (Request ID: fhQtAuS_qa8bj_c6AI0v5)
    

    I get a similar error with push_to_hub

    I logged in to huggingface correctly with the token, and the load_from_hub function works fine.

    opened by LoryPack 5
  • package_to_hub requires OpenGL and xvfb which are not present on newer Mac OS systems

    package_to_hub requires OpenGL and xvfb which are not present on newer Mac OS systems

    Currently package_to_hub works only for OpenGL capable computers. It doesn't support any other option for generating video and it doesn't allow to upload model without a video. All new Mac OSes don't have OpenGL support any more.

    opened by marcin-sobocinski 3
  • Error installing huggingface_sb3

    Error installing huggingface_sb3

    Hi! I'm running this notebook https://github.com/huggingface/deep-rl-class/blob/main/unit1/unit1.ipynb from your DRL series. Installation of some libraries is causing some issues. For huggingface_sb3, it is:

    Collecting huggingface_sb3
      Using cached huggingface_sb3-2.0.0-py3-none-any.whl (7.4 kB)
    Requirement already satisfied: wasabi in ./rl/lib/python3.8/site-packages (from huggingface_sb3) (0.9.1)
    Collecting cloudpickle==1.6
      Using cached cloudpickle-1.6.0-py3-none-any.whl (23 kB)
    Collecting pyyaml==6.0
      Using cached PyYAML-6.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (701 kB)
    Collecting huggingface-hub
      Using cached huggingface_hub-0.6.0-py3-none-any.whl (84 kB)
    Collecting pickle5
      Using cached pickle5-0.0.11.tar.gz (132 kB)
      Preparing metadata (setup.py) ... done
    Collecting typing-extensions>=3.7.4.3
      Using cached typing_extensions-4.2.0-py3-none-any.whl (24 kB)
    Requirement already satisfied: packaging>=20.9 in ./rl/lib/python3.8/site-packages (from huggingface-hub->huggingface_sb3) (21.3)
    Collecting filelock
      Using cached filelock-3.7.0-py3-none-any.whl (10 kB)
    Collecting tqdm
      Using cached tqdm-4.64.0-py2.py3-none-any.whl (78 kB)
    Collecting requests
      Using cached requests-2.27.1-py2.py3-none-any.whl (63 kB)
    Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in ./rl/lib/python3.8/site-packages (from packaging>=20.9->huggingface-hub->huggingface_sb3) (3.0.9)
    Collecting urllib3<1.27,>=1.21.1
      Using cached urllib3-1.26.9-py2.py3-none-any.whl (138 kB)
    Collecting certifi>=2017.4.17
      Using cached certifi-2021.10.8-py2.py3-none-any.whl (149 kB)
    Collecting charset-normalizer~=2.0.0
      Using cached charset_normalizer-2.0.12-py3-none-any.whl (39 kB)
    Collecting idna<4,>=2.5
      Using cached idna-3.3-py3-none-any.whl (61 kB)
    Using legacy 'setup.py install' for pickle5, since package 'wheel' is not installed.
    Installing collected packages: pickle5, certifi, urllib3, typing-extensions, tqdm, pyyaml, idna, filelock, cloudpickle, charset-normalizer, requests, huggingface-hub, huggingface_sb3
      Running setup.py install for pickle5 ... error
      error: subprocess-exited-with-error
      
      × Running setup.py install for pickle5 did not run successfully.
      │ exit code: 1
      ╰─> [27 lines of output]
          running install
          /media/master/support/pip_envs/rl/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
            warnings.warn(
          running build
          running build_py
          creating build
          creating build/lib.linux-x86_64-cpython-38
          creating build/lib.linux-x86_64-cpython-38/pickle5
          copying pickle5/__init__.py -> build/lib.linux-x86_64-cpython-38/pickle5
          copying pickle5/pickle.py -> build/lib.linux-x86_64-cpython-38/pickle5
          copying pickle5/pickletools.py -> build/lib.linux-x86_64-cpython-38/pickle5
          creating build/lib.linux-x86_64-cpython-38/pickle5/test
          copying pickle5/test/pickletester.py -> build/lib.linux-x86_64-cpython-38/pickle5/test
          copying pickle5/test/test_picklebuffer.py -> build/lib.linux-x86_64-cpython-38/pickle5/test
          copying pickle5/test/__init__.py -> build/lib.linux-x86_64-cpython-38/pickle5/test
          copying pickle5/test/test_pickle.py -> build/lib.linux-x86_64-cpython-38/pickle5/test
          running build_ext
          building 'pickle5._pickle' extension
          creating build/temp.linux-x86_64-cpython-38
          creating build/temp.linux-x86_64-cpython-38/pickle5
          x86_64-linux-gnu-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -fPIC -I/media/master/support/pip_envs/rl/include -I/usr/include/python3.8 -c pickle5/_pickle.c -o build/temp.linux-x86_64-cpython-38/pickle5/_pickle.o -std=c99
          In file included from pickle5/_pickle.c:2:
          pickle5/compat.h:1:10: fatal error: Python.h: No such file or directory
              1 | #include "Python.h"
                |          ^~~~~~~~~~
          compilation terminated.
          error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
          [end of output]
      
      note: This error originates from a subprocess, and is likely not a problem with pip.
    error: legacy-install-failure
    
    × Encountered error while trying to install package.
    ╰─> pickle5
    
    note: This is an issue with the package mentioned above, not pip.
    

    I tried installing it with python 3.9 and 3.8 on Ubuntu 22.04 OS.

    Are there any additional requirements to use your library?

    opened by kirilllzaitsev 3
  • generate_replay created a video.mp4 file locally

    generate_replay created a video.mp4 file locally

    This code snippet

    env = VecVideoRecorder(
            eval_env,
            "./",  # Temporary video folder
            record_video_trigger=lambda x: x == 0,
            video_length=video_length,
            name_prefix="",
        )
    

    generated a video file wherever the user is. In the temporary video folder, you can use tempfile.TemporaryDirectory() to automatically create a directory that will be deleted afterwards

    opened by osanseviero 2
  • Rebase repo when pulling

    Rebase repo when pulling

    I think you want to rebase, as we tend to do this in all the mixins in huggingface_hub. I think not having this is what caused this issue: https://github.com/huggingface/deep-rl-class/issues/20.

    opened by nateraw 2
  • Add `VecNormalize` support

    Add `VecNormalize` support

    • add missing type hints
    • fix push_to_hub (bug detected by pytype checker)
    • cleanup
    • add support for VecNormalize

    closes #6

    Demo (and training/loading code): https://huggingface.co/araffin/a2c-Pendulum-v1

    opened by araffin 1
  • Add auto release

    Add auto release

    The behavior with this PR is that once you push a Git tag with v* (usually v1.0.8 for example), which should ideally point to the commit that updates this line https://github.com/huggingface/huggingface_sb3/blob/main/setup.py#L10 (you can push the tag after the commit), it will automatically make a pypi release.

    The only requirement is adding your secret (PYPI_TOKEN_DIST) to the repo settings

    opened by osanseviero 1
  • Allow to pass TensorBoard logs files to package_to_hub

    Allow to pass TensorBoard logs files to package_to_hub

    It's very easy to add TensorBoard logging with SB3, but pushing the files right now needs to be done manually. As an alternative, we could add a param to package_to_hub to pass the logs.

    Related: https://github.com/huggingface/deep-rl-class/pull/19

    opened by osanseviero 0
  • Don't crash when making videos causes problems

    Don't crash when making videos causes problems

    At the moment, if generate_replay fails, the whole package_to_hub method fails. Ideally it would still push the metrics and other related information even if no video is generated

    opened by osanseviero 0
  • Huggingface_SB3 v2.0

    Huggingface_SB3 v2.0

    👋 so here's the SB3 v2.0:

    With our new version we can use package_to_hub method that:

    1. Save the model
    2. Evaluate the model and generate a results.json
    3. Generate a model card
    4. Record a replay video of the agent
    5. Push everything to the hub Here's an example : https://huggingface.co/ThomasSimonini/TEST2-Colab-ppo-LunarLander-v2 (very small training so the agent is bad)

    If you want to try some examples directly on colab I've made a small test colab: https://colab.research.google.com/drive/1FhZ1w7smqPo8GQcW5qb2HmkggZVuok57?usp=sharing

    The PyPi update is also automated thanks to @osanseviero

    A big thanks to Omar who made a lot of tests with the library

    I need a little bit of feedback for the documentation, I think it's not very clear.

    • I explain the 2 cases: downstream and upstream
    • In case 3-4 I explain how to use xvfb if you use colab or vm (because you don't have a screen to render so you can't generate a video without xvfb).

    WDYT? Thanks

    opened by simoninithomas 0
Releases(v2.2.4)
  • v2.2.4(Oct 13, 2022)

    What's Changed

    • Loosen the requirements by @araffin in https://github.com/huggingface/huggingface_sb3/pull/19

    Full Changelog: https://github.com/huggingface/huggingface_sb3/compare/v2.2.3...v2.2.4

    Source code(tar.gz)
    Source code(zip)
  • v2.2.3(Aug 5, 2022)

    Cloudpickle is 1.3 by default on Colab. We need at minimum 1.6 for package_to_hub and load_from_hub to work correctly.

    Full Changelog: https://github.com/huggingface/huggingface_sb3/compare/v2.2.2...v2.2.3

    Source code(tar.gz)
    Source code(zip)
  • v2.2.2(Aug 1, 2022)

    What's Changed

    • V2.2.2 by @simoninithomas in https://github.com/huggingface/huggingface_sb3/pull/17
    • Pinning this dependency leads to some uploading problems. We removed it

    Full Changelog: https://github.com/huggingface/huggingface_sb3/compare/v2.2.1...v2.2.2

    Source code(tar.gz)
    Source code(zip)
  • v2.2.1(Jul 8, 2022)

    What's Changed

    • Notebook fixes by @ernestum in https://github.com/huggingface/huggingface_sb3/pull/12
    • Environment name normalization and explicit naming schemes by @ernestum in https://github.com/huggingface/huggingface_sb3/pull/13
    • Use new upload_folder API by @osanseviero in https://github.com/huggingface/huggingface_sb3/pull/15

    New Contributors

    • @ernestum made their first contribution in https://github.com/huggingface/huggingface_sb3/pull/12

    Full Changelog: https://github.com/huggingface/huggingface_sb3/compare/v2.1.1...v2.2

    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(May 20, 2022)

    What's Changed

    • Use make_vec_env to create envs by @araffin in https://github.com/huggingface/huggingface_sb3/pull/3
    • Rebase repo when pulling by @nateraw in https://github.com/huggingface/huggingface_sb3/pull/7
    • Fix record video for RecurrentPPO by @araffin in https://github.com/huggingface/huggingface_sb3/pull/8
    • Add VecNormalize support by @araffin in https://github.com/huggingface/huggingface_sb3/pull/10

    New Contributors

    • @araffin made their first contribution in https://github.com/huggingface/huggingface_sb3/pull/3
    • @nateraw made their first contribution in https://github.com/huggingface/huggingface_sb3/pull/7

    Full Changelog: https://github.com/huggingface/huggingface_sb3/compare/v2.0.0...v2.1.0

    Source code(tar.gz)
    Source code(zip)
Owner
Hugging Face
The AI community building the future.
Hugging Face
This code is the implementation of the paper "Coherence-Based Distributed Document Representation Learning for Scientific Documents".

Introduction This code is the implementation of the paper "Coherence-Based Distributed Document Representation Learning for Scientific Documents". If

tsc 0 Jan 11, 2022
Set of methods to ensemble boxes from different object detection models, including implementation of "Weighted boxes fusion (WBF)" method.

Set of methods to ensemble boxes from different object detection models, including implementation of "Weighted boxes fusion (WBF)" method.

1.4k Jan 05, 2023
GPOEO is a micro-intrusive GPU online energy optimization framework for iterative applications

GPOEO GPOEO is a micro-intrusive GPU online energy optimization framework for iterative applications. We also implement ODPP [1] as a comparison. [1]

瑞雪轻飏 8 Sep 10, 2022
《Rethinking Sptil Dimensions of Vision Trnsformers》(2021)

Rethinking Spatial Dimensions of Vision Transformers Byeongho Heo, Sangdoo Yun, Dongyoon Han, Sanghyuk Chun, Junsuk Choe, Seong Joon Oh | Paper NAVER

NAVER AI 224 Dec 27, 2022
This is the dataset and code release of the OpenRooms Dataset.

This is the dataset and code release of the OpenRooms Dataset.

Visual Intelligence Lab of UCSD 95 Jan 08, 2023
Image Segmentation using U-Net, U-Net with skip connections and M-Net architectures

Brain-Image-Segmentation Segmentation of brain tissues in MRI image has a number of applications in diagnosis, surgical planning, and treatment of bra

Angad Bajwa 8 Oct 27, 2022
🙄 Difficult algorithm, Simple code.

🎉TensorFlow2.0-Examples🎉! "Talk is cheap, show me the code." ----- Linus Torvalds Created by YunYang1994 This tutorial was designed for easily divin

1.7k Dec 25, 2022
a short visualisation script for pyvideo data

PyVideo Speakers A CLI that visualises repeat speakers from events listed in https://github.com/pyvideo/data Not terribly efficient, but you know. Ins

Katie McLaughlin 3 Nov 24, 2021
Hippocampal segmentation using the UNet network for each axis

Hipposeg Hippocampal segmentation using the UNet network for each axis, inspired by https://github.com/MICLab-Unicamp/e2dhipseg Red: False Positive Gr

Juan Carlos Aguirre Arango 0 Sep 02, 2021
DCA - Official Python implementation of Delaunay Component Analysis algorithm

Delaunay Component Analysis (DCA) Official Python implementation of the Delaunay

Petra Poklukar 9 Sep 06, 2022
🚗 INGI Dakar 2K21 - Be the first one on the finish line ! 🚗

🚗 INGI Dakar 2K21 - Be the first one on the finish line ! 🚗 This year's first semester Club Info challenge will put you at the head of a car racing

ClubINFO INGI (UCLouvain) 6 Dec 10, 2021
gym-anm is a framework for designing reinforcement learning (RL) environments that model Active Network Management (ANM) tasks in electricity distribution networks.

gym-anm is a framework for designing reinforcement learning (RL) environments that model Active Network Management (ANM) tasks in electricity distribution networks. It is built on top of the OpenAI G

Robin Henry 99 Dec 12, 2022
Tackling data scarcity in Speech Translation using zero-shot multilingual Machine Translation techniques

Tackling data scarcity in Speech Translation using zero-shot multilingual Machine Translation techniques This repository is derived from the NMTGMinor

Tu Anh Dinh 1 Sep 07, 2022
TRIQ implementation

TRIQ Implementation TF-Keras implementation of TRIQ as described in Transformer for Image Quality Assessment. Installation Clone this repository. Inst

Junyong You 115 Dec 30, 2022
Weakly Supervised Learning of Instance Segmentation with Inter-pixel Relations, CVPR 2019 (Oral)

Weakly Supervised Learning of Instance Segmentation with Inter-pixel Relations The code of: Weakly Supervised Learning of Instance Segmentation with I

Jiwoon Ahn 472 Dec 29, 2022
The code for our paper "NSP-BERT: A Prompt-based Zero-Shot Learner Through an Original Pre-training Task —— Next Sentence Prediction"

The code for our paper "NSP-BERT: A Prompt-based Zero-Shot Learner Through an Original Pre-training Task —— Next Sentence Prediction"

Sun Yi 201 Nov 21, 2022
High-Resolution Image Synthesis with Latent Diffusion Models

Latent Diffusion Models arXiv | BibTeX High-Resolution Image Synthesis with Latent Diffusion Models Robin Rombach*, Andreas Blattmann*, Dominik Lorenz

CompVis Heidelberg 5.6k Dec 30, 2022
Probabilistic Gradient Boosting Machines

PGBM Probabilistic Gradient Boosting Machines (PGBM) is a probabilistic gradient boosting framework in Python based on PyTorch/Numba, developed by Air

Olivier Sprangers 112 Dec 28, 2022
BARF: Bundle-Adjusting Neural Radiance Fields 🤮 (ICCV 2021 oral)

BARF 🤮 : Bundle-Adjusting Neural Radiance Fields Chen-Hsuan Lin, Wei-Chiu Ma, Antonio Torralba, and Simon Lucey IEEE International Conference on Comp

Chen-Hsuan Lin 539 Dec 28, 2022
Face Library is an open source package for accurate and real-time face detection and recognition

Face Library Face Library is an open source package for accurate and real-time face detection and recognition. The package is built over OpenCV and us

52 Nov 09, 2022