forked from microsoft/CyberBattleSim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notebook_benchmark.py
237 lines (212 loc) · 6.24 KB
/
notebook_benchmark.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""Benchmark all the baseline agents
on a given CyberBattleSim environment and compare
them to the dumb 'random agent' baseline.
NOTE: You can run this `.py`-notebook directly from VSCode.
You can also generate a traditional Jupyter Notebook
using the VSCode command `Export Currenty Python File As Jupyter Notebook`.
"""
# pylint: disable=invalid-name
# %%
import sys
import logging
import gym
import cyberbattle.agents.baseline.learner as learner
import cyberbattle.agents.baseline.plotting as p
import cyberbattle.agents.baseline.agent_wrapper as w
import cyberbattle.agents.baseline.agent_randomcredlookup as rca
import cyberbattle.agents.baseline.agent_tabularqlearning as tqa
import cyberbattle.agents.baseline.agent_dql as dqla
from cyberbattle.agents.baseline.agent_wrapper import Verbosity
logging.basicConfig(stream=sys.stdout, level=logging.ERROR, format="%(levelname)s: %(message)s")
# %% {"tags": ["parameters"]}
# Papermill notebook parameters
#############
# gymid = 'CyberBattleTiny-v0'
#############
gymid = "CyberBattleToyCtf-v0"
env_size = None
iteration_count = 1500
training_episode_count = 20
eval_episode_count = 10
maximum_node_count = 12
maximum_total_credentials = 10
#############
# gymid = "CyberBattleChain-v0"
# env_size = 10
# iteration_count = 9000
# training_episode_count = 50
# eval_episode_count = 5
# maximum_node_count = 22
# maximum_total_credentials = 22
# %%
# Load the Gym environment
if env_size:
gym_env = gym.make(gymid, size=env_size)
else:
gym_env = gym.make(gymid)
ep = w.EnvironmentBounds.of_identifiers(
maximum_node_count=maximum_node_count,
maximum_total_credentials=maximum_total_credentials,
identifiers=gym_env.identifiers
)
# %%
debugging = False
if debugging:
print(f"port_count = {ep.port_count}, property_count = {ep.property_count}")
gym_env.environment
# training_env.environment.plot_environment_graph()
gym_env.environment.network.nodes
gym_env.action_space
gym_env.action_space.sample()
gym_env.observation_space.sample()
o0 = gym_env.reset()
o_test, r, d, i = gym_env.step(gym_env.sample_valid_action())
o0 = gym_env.reset()
o0.keys()
fe_example = w.RavelEncoding(ep, [w.Feature_active_node_properties(ep), w.Feature_discovered_node_count(ep)])
a = w.StateAugmentation(o0)
w.Feature_discovered_ports(ep).get(a, None)
fe_example.encode_at(a, 0)
# %%
# Evaluate a random agent that opportunistically exploits
# credentials gathere in its local cache
credlookup_run = learner.epsilon_greedy_search(
gym_env,
ep,
learner=rca.CredentialCacheExploiter(),
episode_count=10,
iteration_count=iteration_count,
epsilon=0.90,
render=False,
epsilon_exponential_decay=10000,
epsilon_minimum=0.10,
verbosity=Verbosity.Quiet,
title="Credential lookups (ϵ-greedy)"
)
# %%
# Evaluate a Tabular Q-learning agent
tabularq_run = learner.epsilon_greedy_search(
gym_env,
ep,
learner=tqa.QTabularLearner(
ep,
gamma=0.015, learning_rate=0.01, exploit_percentile=100),
episode_count=training_episode_count,
iteration_count=iteration_count,
epsilon=0.90,
epsilon_exponential_decay=5000,
epsilon_minimum=0.01,
verbosity=Verbosity.Quiet,
render=False,
plot_episodes_length=False,
title="Tabular Q-learning"
)
# %%
# Evaluate an agent that exploits the Q-table learnt above
tabularq_exploit_run = learner.epsilon_greedy_search(
gym_env,
ep,
learner=tqa.QTabularLearner(
ep,
trained=tabularq_run['learner'],
gamma=0.0,
learning_rate=0.0,
exploit_percentile=90),
episode_count=eval_episode_count,
iteration_count=iteration_count,
epsilon=0.0,
render=False,
verbosity=Verbosity.Quiet,
title="Exploiting Q-matrix"
)
# %%
# Evaluate the Deep Q-learning agent
dql_run = learner.epsilon_greedy_search(
cyberbattle_gym_env=gym_env,
environment_properties=ep,
learner=dqla.DeepQLearnerPolicy(
ep=ep,
gamma=0.015,
replay_memory_size=10000,
target_update=10,
batch_size=512,
# torch default learning rate is 1e-2
# a large value helps converge in less episodes
learning_rate=0.01
),
episode_count=training_episode_count,
iteration_count=iteration_count,
epsilon=0.90,
epsilon_exponential_decay=5000,
epsilon_minimum=0.10,
verbosity=Verbosity.Quiet,
render=False,
plot_episodes_length=False,
title="DQL"
)
# %%
# Evaluate an agent that exploits the Q-function learnt above
dql_exploit_run = learner.epsilon_greedy_search(
gym_env,
ep,
learner=dql_run['learner'],
episode_count=eval_episode_count,
iteration_count=iteration_count,
epsilon=0.0,
epsilon_minimum=0.00,
render=False,
plot_episodes_length=False,
verbosity=Verbosity.Quiet,
title="Exploiting DQL"
)
# %%
# Evaluate the random agent
random_run = learner.epsilon_greedy_search(
gym_env,
ep,
learner=learner.RandomPolicy(),
episode_count=eval_episode_count,
iteration_count=iteration_count,
epsilon=1.0, # purely random
render=False,
verbosity=Verbosity.Quiet,
plot_episodes_length=False,
title="Random search"
)
# %%
# Compare and plot results for all the agents
all_runs = [
random_run,
credlookup_run,
tabularq_run,
tabularq_exploit_run,
dql_run,
dql_exploit_run
]
# Plot averaged cumulative rewards for DQL vs Random vs DQL-Exploit
themodel = dqla.CyberBattleStateActionModel(ep)
p.plot_averaged_cummulative_rewards(
all_runs=all_runs,
title=f'Benchmark -- max_nodes={ep.maximum_node_count}, episodes={eval_episode_count},\n'
f'State: {[f.name() for f in themodel.state_space.feature_selection]} '
f'({len(themodel.state_space.feature_selection)}\n'
f"Action: abstract_action ({themodel.action_space.flat_size()})")
# %%
contenders = [
credlookup_run,
tabularq_run,
dql_run,
dql_exploit_run
]
p.plot_episodes_length(contenders)
p.plot_averaged_cummulative_rewards(
title=f'Agent Benchmark top contenders\n'
f'max_nodes:{ep.maximum_node_count}\n',
all_runs=contenders)
# %%
# Plot cumulative rewards for all episodes
for r in contenders:
p.plot_all_episodes(r)
# %%