Skip to content

Commit d8cc795

Browse files
authored
Type check with pytype (#565)
* Configure pytype in CI * Fix pytype types * gitignore: ignore pytype cache * Update Docker * fix stray import error * PEP 561 compliance * Update changelog * [Temporary] Explicitly install pytype * Simplify Dockerfile * Set appropriate python_version for pytype * Update Docker * Lint * Update Docker tags * Fix type error (mujoco_py not available in Docker) * [Temporary] Use my Docker image * Fix cmd_util after Gym upgrade * Use new JRE so that Codacy Coverage uploader can function * Update Docker tags * Change return type to float * try-except for backward compatibility * add error message * Update Docker tag for Travis * fix type errors * Update Docker install instructions * Document type checking * Do Codacy uploads from PR build (unless in fork)
1 parent be6ef31 commit d8cc795

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+179
-142
lines changed

.dockerignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.gitignore

.github/PULL_REQUEST_TEMPLATE.md

+1
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,6 @@
2424
- [ ] My change requires a change to the documentation.
2525
- [ ] I have updated the tests accordingly (*required for a bug fix or a new feature*).
2626
- [ ] I have updated the documentation accordingly.
27+
- [ ] I have ensured `pytest` and `pytype` both pass.
2728

2829
<!--- This Template is an edited version of the one from https://github.com/evilsocket/pwnagotchi/ -->

.gitignore

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*.py~
55
*.bak
66
.pytest_cache
7+
.pytype
78
.DS_Store
89
.idea
910
.coverage
@@ -19,13 +20,11 @@ keys/
1920

2021
# Virtualenv
2122
/env
22-
23+
/venv
2324

2425
*.sublime-project
2526
*.sublime-workspace
2627

27-
.idea
28-
2928
logs/
3029

3130
.ipynb_checkpoints

.travis.yml

+6-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ python:
44

55
env:
66
global:
7-
- DOCKER_IMAGE=araffin/stable-baselines-cpu:v2.7.1
7+
- DOCKER_IMAGE=stablebaselines/stable-baselines-cpu:v2.9.0
88

99
notifications:
1010
email: false
@@ -41,8 +41,12 @@ jobs:
4141
script:
4242
- 'docker run -it --rm --mount src=$(pwd),target=/root/code/stable-baselines,type=bind ${DOCKER_IMAGE} bash -c "cd /root/code/stable-baselines/ && pip install .[docs] && pushd docs/ && make clean && make html"'
4343

44+
- name: "Type Checking"
45+
script:
46+
- 'docker run --rm --mount src=$(pwd),target=/root/code/stable-baselines,type=bind ${DOCKER_IMAGE} bash -c "cd /root/code/stable-baselines/ && pytype"'
47+
4448
- stage: Codacy Trigger
4549
if: type != pull_request
4650
script:
4751
# When all test coverage reports have been uploaded, instruct Codacy to start analysis.
48-
- 'docker run -it --rm --network host --ipc=host --mount src=$(pwd),target=/root/code/stable-baselines,type=bind --env CODACY_PROJECT_TOKEN=${CODACY_PROJECT_TOKEN} ${DOCKER_IMAGE} bash -c "cd /root/code/stable-baselines/ && /root/code/codacy-coverage-reporter final"'
52+
- 'docker run -it --rm --network host --ipc=host --mount src=$(pwd),target=/root/code/stable-baselines,type=bind --env CODACY_PROJECT_TOKEN=${CODACY_PROJECT_TOKEN} ${DOCKER_IMAGE} bash -c "cd /root/code/stable-baselines/ && java -jar /root/code/codacy-coverage-reporter.jar final"'

CONTRIBUTING.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ All new features must add tests in the `tests/` folder ensuring that everything
8888
We use [pytest](https://pytest.org/).
8989
Also, when a bug fix is proposed, tests should be added to avoid regression.
9090

91-
To run tests:
91+
To run tests with `pytest` and type checking with `pytype`:
9292

9393
```
9494
./scripts/run_tests.sh

Dockerfile

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
ARG PARENT_IMAGE
2+
ARG USE_GPU
3+
FROM $PARENT_IMAGE
4+
5+
RUN apt-get -y update \
6+
&& apt-get -y install \
7+
curl \
8+
cmake \
9+
default-jre \
10+
git \
11+
jq \
12+
python-dev \
13+
python-pip \
14+
python3-dev \
15+
libfontconfig1 \
16+
libglib2.0-0 \
17+
libsm6 \
18+
libxext6 \
19+
libxrender1 \
20+
libopenmpi-dev \
21+
zlib1g-dev \
22+
&& apt-get clean \
23+
&& rm -rf /var/lib/apt/lists/*
24+
25+
ENV CODE_DIR /root/code
26+
ENV VENV /root/venv
27+
28+
COPY ./setup.py /root/code/setup.py
29+
RUN \
30+
mkdir -p ${CODE_DIR}/stable_baselines && \
31+
pip install virtualenv && \
32+
virtualenv $VENV --python=python3 && \
33+
. $VENV/bin/activate && \
34+
cd $CODE_DIR && \
35+
pip install --upgrade pip && \
36+
if [[ $USE_GPU == "True" ]]; then \
37+
TENSORFLOW_PACKAGE="tensorflow-gpu==1.8.0"; \
38+
else \
39+
TENSORFLOW_PACKAGE="tensorflow==1.8.0"; \
40+
fi; \
41+
pip install ${TENSORFLOW_PACKAGE} && \
42+
pip install -e .[mpi,tests] && \
43+
pip install codacy-coverage && \
44+
rm -rf $HOME/.cache/pip
45+
46+
ENV PATH=$VENV/bin:$PATH
47+
48+
# Codacy code coverage report: used for partial code coverage reporting
49+
RUN cd $CODE_DIR && \
50+
curl -Ls -o codacy-coverage-reporter.jar "$(curl -Ls https://api.github.com/repos/codacy/codacy-coverage-reporter/releases/latest | jq -r '.assets | map({name, browser_download_url} | select(.name | (contains("codacy-coverage-reporter") and endswith("assembly.jar")))) | .[0].browser_download_url')"
51+
52+
CMD /bin/bash

docker/Dockerfile.cpu

-39
This file was deleted.

docker/Dockerfile.gpu

-32
This file was deleted.

docs/guide/install.rst

+6-6
Original file line numberDiff line numberDiff line change
@@ -101,13 +101,13 @@ GPU image (requires `nvidia-docker`_):
101101

102102
.. code-block:: bash
103103
104-
docker pull araffin/stable-baselines
104+
docker pull stablebaselines/stable-baselines
105105
106106
CPU only:
107107

108108
.. code-block:: bash
109109
110-
docker pull araffin/stable-baselines-cpu
110+
docker pull stablebaselines/stable-baselines-cpu
111111
112112
Build the Docker Images
113113
~~~~~~~~~~~~~~~~~~~~~~~~
@@ -116,13 +116,13 @@ Build GPU image (with nvidia-docker):
116116

117117
.. code-block:: bash
118118
119-
docker build . -f docker/Dockerfile.gpu -t stable-baselines
119+
USE_GPU=True ./scripts/build_docker.sh
120120
121121
Build CPU image:
122122

123123
.. code-block:: bash
124124
125-
docker build . -f docker/Dockerfile.cpu -t stable-baselines-cpu
125+
./scripts/build_docker.sh
126126
127127
Note: if you are using a proxy, you need to pass extra params during
128128
build and do some `tweaks`_:
@@ -138,7 +138,7 @@ Run the nvidia-docker GPU image
138138

139139
.. code-block:: bash
140140
141-
docker run -it --runtime=nvidia --rm --network host --ipc=host --name test --mount src="$(pwd)",target=/root/code/stable-baselines,type=bind araffin/stable-baselines bash -c 'cd /root/code/stable-baselines/ && pytest tests/'
141+
docker run -it --runtime=nvidia --rm --network host --ipc=host --name test --mount src="$(pwd)",target=/root/code/stable-baselines,type=bind stablebaselines/stable-baselines bash -c 'cd /root/code/stable-baselines/ && pytest tests/'
142142
143143
Or, with the shell file:
144144

@@ -150,7 +150,7 @@ Run the docker CPU image
150150

151151
.. code-block:: bash
152152
153-
docker run -it --rm --network host --ipc=host --name test --mount src="$(pwd)",target=/root/code/stable-baselines,type=bind araffin/stable-baselines-cpu bash -c 'cd /root/code/stable-baselines/ && pytest tests/'
153+
docker run -it --rm --network host --ipc=host --name test --mount src="$(pwd)",target=/root/code/stable-baselines,type=bind stablebaselines/stable-baselines-cpu bash -c 'cd /root/code/stable-baselines/ && pytest tests/'
154154
155155
Or, with the shell file:
156156

docs/misc/changelog.rst

+3
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,15 @@ New Features:
1919
- Add `n_cpu_tf_sess` to model constructor to choose the number of threads used by Tensorflow
2020
- `VecNormalize` now supports being pickled and unpickled.
2121
- Add parameter `exploration_initial_eps` to DQN. (@jdossgollin)
22+
- Add type checking and PEP 561 compliance.
23+
Note: most functions are still not annotated, this will be a gradual process.
2224

2325
Bug Fixes:
2426
^^^^^^^^^^
2527
- Fix seeding, so it is now possible to have deterministic results on cpu
2628
- Fix a bug in DDPG where `predict` method with `deterministic=False` would fail
2729
- Fix a bug in TRPO: mean_losses was not initialized causing the logger to crash when there was no gradients (@MarvineGothic)
30+
- Fix a bug in `cmd_util` from API change in recent Gym versions
2831

2932
Deprecations:
3033
^^^^^^^^^^^^^

scripts/build_docker.sh

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#!/bin/bash
2+
3+
CPU_PARENT=ubuntu:16.04
4+
GPU_PARENT=nvidia/cuda:9.0-cudnn7-runtime-ubuntu16.04
5+
6+
TAG=stablebaselines/stable-baselines
7+
VERSION=v2.9.0
8+
9+
if [[ ${USE_GPU} == "True" ]]; then
10+
PARENT=${GPU_PARENT}
11+
else
12+
PARENT=${CPU_PARENT}
13+
TAG="${TAG}-cpu"
14+
fi
15+
16+
docker build --build-arg PARENT_IMAGE=${PARENT} -t ${TAG}:${VERSION} .
17+

scripts/run_docker_cpu.sh

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ cmd_line="$@"
66
echo "Executing in the docker (cpu image):"
77
echo $cmd_line
88

9-
109
docker run -it --rm --network host --ipc=host \
11-
--mount src=$(pwd),target=/root/code/stable-baselines,type=bind araffin/stable-baselines-cpu:v2.7.1 \
10+
--mount src=$(pwd),target=/root/code/stable-baselines,type=bind stablebaselines/stable-baselines-cpu:v2.9.0 \
1211
bash -c "cd /root/code/stable-baselines/ && $cmd_line"

scripts/run_docker_gpu.sh

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ echo $cmd_line
88

99

1010
docker run -it --runtime=nvidia --rm --network host --ipc=host \
11-
--mount src=$(pwd),target=/root/code/stable-baselines,type=bind araffin/stable-baselines:v2.7.1 \
11+
--mount src=$(pwd),target=/root/code/stable-baselines,type=bind stablebaselines/stable-baselines:v2.9.0 \
1212
bash -c "cd /root/code/stable-baselines/ && $cmd_line"

scripts/run_tests.sh

+1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
#!/bin/bash
22
python -m pytest --cov-config .coveragerc --cov-report html --cov-report term --cov=. -v
3+
pytype

scripts/run_tests_travis.sh

+4-7
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,15 @@ TEST_GLOB=$1
1818
set -e # exit immediately on any error
1919

2020
# For pull requests from fork, Codacy token is not available, leading to build failure
21-
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
21+
if [[ ${CODACY_PROJECT_TOKEN} = "" ]]; then
22+
echo "WARNING: CODACY_PROJECT_TOKEN not set. Skipping Codacy upload."
23+
echo "(This is normal when building in a fork and can be ignored.)"
2224
${DOCKER_CMD} ${DOCKER_IMAGE} \
2325
bash -c "${BASH_CMD} && \
2426
pytest --cov-config .coveragerc --cov-report term --cov=. -v tests/test_${TEST_GLOB}"
2527
else
26-
if [[ ${CODACY_PROJECT_TOKEN} = "" ]]; then
27-
echo "Need CODACY_PROJECT_TOKEN environment variable to be set."
28-
exit 1
29-
fi
30-
3128
${DOCKER_CMD} --env CODACY_PROJECT_TOKEN=${CODACY_PROJECT_TOKEN} ${DOCKER_IMAGE} \
3229
bash -c "${BASH_CMD} && \
3330
pytest --cov-config .coveragerc --cov-report term --cov-report xml --cov=. -v tests/test_${TEST_GLOB} && \
34-
/root/code/codacy-coverage-reporter report -l python -r coverage.xml --partial"
31+
java -jar /root/code/codacy-coverage-reporter.jar report -l python -r coverage.xml --partial"
3532
fi

setup.cfg

+4
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,7 @@ filterwarnings =
1616
# Gym warnings
1717
ignore:Parameters to load are deprecated.:DeprecationWarning
1818
ignore:the imp module is deprecated in favour of importlib:PendingDeprecationWarning
19+
20+
[pytype]
21+
inputs = stable_baselines
22+
python_version = 3.5

setup.py

+4
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,9 @@
105105
setup(name='stable_baselines',
106106
packages=[package for package in find_packages()
107107
if package.startswith('stable_baselines')],
108+
package_data={
109+
'stable_baselines': ['py.typed'],
110+
},
108111
install_requires=[
109112
'gym[atari,classic_control]>=0.10.9',
110113
'scipy',
@@ -124,6 +127,7 @@
124127
'pytest-cov',
125128
'pytest-env',
126129
'pytest-xdist',
130+
'pytype',
127131
],
128132
'docs': [
129133
'sphinx',

stable_baselines/acer/acer_simple.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import time
2+
import warnings
23

34
import numpy as np
45
import tensorflow as tf
@@ -538,7 +539,9 @@ def learn(self, total_timesteps, callback=None, log_interval=100, tb_log_name="A
538539
logger.record_tabular(name, float(val))
539540
logger.dump_tabular()
540541

541-
if self.replay_ratio > 0 and buffer.has_atleast(self.replay_start):
542+
if (self.replay_ratio > 0 and
543+
buffer is not None and
544+
buffer.has_atleast(self.replay_start)):
542545
samples_number = np.random.poisson(self.replay_ratio)
543546
for _ in range(samples_number):
544547
# get obs, actions, rewards, mus, dones from buffer.

stable_baselines/acktr/acktr.py

+2
Original file line numberDiff line numberDiff line change
@@ -337,12 +337,14 @@ def learn(self, total_timesteps, callback=None, log_interval=100, tb_log_name="A
337337
ep_info_buf = deque(maxlen=100)
338338

339339
for update in range(1, total_timesteps // self.n_batch + 1):
340+
# pytype:disable=bad-unpacking
340341
# true_reward is the reward without discount
341342
if isinstance(runner, PPO2Runner):
342343
# We are using GAE
343344
obs, returns, masks, actions, values, _, states, ep_infos, true_reward = runner.run()
344345
else:
345346
obs, states, returns, masks, actions, values, ep_infos, true_reward = runner.run()
347+
# pytype:enable=bad-unpacking
346348

347349
ep_info_buf.extend(ep_infos)
348350
policy_loss, value_loss, policy_entropy = self._train_step(obs, states, returns, masks, actions, values,

0 commit comments

Comments
 (0)