dynamic_tf_policy.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. import logging
  2. import re
  3. from collections import OrderedDict, namedtuple
  4. from typing import Callable, Dict, List, Optional, Tuple, Type, Union
  5. import gymnasium as gym
  6. import tree # pip install dm_tree
  7. from ray._common.deprecation import (
  8. DEPRECATED_VALUE,
  9. deprecation_warning,
  10. )
  11. from ray.rllib.models.catalog import ModelCatalog
  12. from ray.rllib.models.modelv2 import ModelV2
  13. from ray.rllib.models.tf.tf_action_dist import TFActionDistribution
  14. from ray.rllib.policy.policy import Policy
  15. from ray.rllib.policy.sample_batch import SampleBatch
  16. from ray.rllib.policy.tf_policy import TFPolicy
  17. from ray.rllib.policy.view_requirement import ViewRequirement
  18. from ray.rllib.utils import force_list
  19. from ray.rllib.utils.annotations import OldAPIStack, override
  20. from ray.rllib.utils.debug import summarize
  21. from ray.rllib.utils.framework import try_import_tf
  22. from ray.rllib.utils.metrics import (
  23. DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY,
  24. NUM_GRAD_UPDATES_LIFETIME,
  25. )
  26. from ray.rllib.utils.spaces.space_utils import get_dummy_batch_for_space
  27. from ray.rllib.utils.tf_utils import get_placeholder
  28. from ray.rllib.utils.typing import (
  29. AlgorithmConfigDict,
  30. LocalOptimizer,
  31. ModelGradients,
  32. TensorType,
  33. )
  34. from ray.util.debug import log_once
  35. tf1, tf, tfv = try_import_tf()
  36. logger = logging.getLogger(__name__)
  37. # Variable scope in which created variables will be placed under.
  38. TOWER_SCOPE_NAME = "tower"
  39. @OldAPIStack
  40. class DynamicTFPolicy(TFPolicy):
  41. """A TFPolicy that auto-defines placeholders dynamically at runtime.
  42. Do not sub-class this class directly (neither should you sub-class
  43. TFPolicy), but rather use rllib.policy.tf_policy_template.build_tf_policy
  44. to generate your custom tf (graph-mode or eager) Policy classes.
  45. """
  46. def __init__(
  47. self,
  48. obs_space: gym.spaces.Space,
  49. action_space: gym.spaces.Space,
  50. config: AlgorithmConfigDict,
  51. loss_fn: Callable[
  52. [Policy, ModelV2, Type[TFActionDistribution], SampleBatch], TensorType
  53. ],
  54. *,
  55. stats_fn: Optional[
  56. Callable[[Policy, SampleBatch], Dict[str, TensorType]]
  57. ] = None,
  58. grad_stats_fn: Optional[
  59. Callable[[Policy, SampleBatch, ModelGradients], Dict[str, TensorType]]
  60. ] = None,
  61. before_loss_init: Optional[
  62. Callable[
  63. [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], None
  64. ]
  65. ] = None,
  66. make_model: Optional[
  67. Callable[
  68. [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict],
  69. ModelV2,
  70. ]
  71. ] = None,
  72. action_sampler_fn: Optional[
  73. Callable[
  74. [TensorType, List[TensorType]],
  75. Union[
  76. Tuple[TensorType, TensorType],
  77. Tuple[TensorType, TensorType, TensorType, List[TensorType]],
  78. ],
  79. ]
  80. ] = None,
  81. action_distribution_fn: Optional[
  82. Callable[
  83. [Policy, ModelV2, TensorType, TensorType, TensorType],
  84. Tuple[TensorType, type, List[TensorType]],
  85. ]
  86. ] = None,
  87. existing_inputs: Optional[Dict[str, "tf1.placeholder"]] = None,
  88. existing_model: Optional[ModelV2] = None,
  89. get_batch_divisibility_req: Optional[Callable[[Policy], int]] = None,
  90. obs_include_prev_action_reward=DEPRECATED_VALUE,
  91. ):
  92. """Initializes a DynamicTFPolicy instance.
  93. Initialization of this class occurs in two phases and defines the
  94. static graph.
  95. Phase 1: The model is created and model variables are initialized.
  96. Phase 2: A fake batch of data is created, sent to the trajectory
  97. postprocessor, and then used to create placeholders for the loss
  98. function. The loss and stats functions are initialized with these
  99. placeholders.
  100. Args:
  101. observation_space: Observation space of the policy.
  102. action_space: Action space of the policy.
  103. config: Policy-specific configuration data.
  104. loss_fn: Function that returns a loss tensor for the policy graph.
  105. stats_fn: Optional callable that - given the policy and batch
  106. input tensors - returns a dict mapping str to TF ops.
  107. These ops are fetched from the graph after loss calculations
  108. and the resulting values can be found in the results dict
  109. returned by e.g. `Algorithm.train()` or in tensorboard (if TB
  110. logging is enabled).
  111. grad_stats_fn: Optional callable that - given the policy, batch
  112. input tensors, and calculated loss gradient tensors - returns
  113. a dict mapping str to TF ops. These ops are fetched from the
  114. graph after loss and gradient calculations and the resulting
  115. values can be found in the results dict returned by e.g.
  116. `Algorithm.train()` or in tensorboard (if TB logging is
  117. enabled).
  118. before_loss_init: Optional function to run prior to
  119. loss init that takes the same arguments as __init__.
  120. make_model: Optional function that returns a ModelV2 object
  121. given policy, obs_space, action_space, and policy config.
  122. All policy variables should be created in this function. If not
  123. specified, a default model will be created.
  124. action_sampler_fn: A callable returning either a sampled action and
  125. its log-likelihood or a sampled action, its log-likelihood,
  126. action distribution inputs and updated state given Policy,
  127. ModelV2, observation inputs, explore, and is_training.
  128. Provide `action_sampler_fn` if you would like to have full
  129. control over the action computation step, including the
  130. model forward pass, possible sampling from a distribution,
  131. and exploration logic.
  132. Note: If `action_sampler_fn` is given, `action_distribution_fn`
  133. must be None. If both `action_sampler_fn` and
  134. `action_distribution_fn` are None, RLlib will simply pass
  135. inputs through `self.model` to get distribution inputs, create
  136. the distribution object, sample from it, and apply some
  137. exploration logic to the results.
  138. The callable takes as inputs: Policy, ModelV2, obs_batch,
  139. state_batches (optional), seq_lens (optional),
  140. prev_actions_batch (optional), prev_rewards_batch (optional),
  141. explore, and is_training.
  142. action_distribution_fn: A callable returning distribution inputs
  143. (parameters), a dist-class to generate an action distribution
  144. object from, and internal-state outputs (or an empty list if
  145. not applicable).
  146. Provide `action_distribution_fn` if you would like to only
  147. customize the model forward pass call. The resulting
  148. distribution parameters are then used by RLlib to create a
  149. distribution object, sample from it, and execute any
  150. exploration logic.
  151. Note: If `action_distribution_fn` is given, `action_sampler_fn`
  152. must be None. If both `action_sampler_fn` and
  153. `action_distribution_fn` are None, RLlib will simply pass
  154. inputs through `self.model` to get distribution inputs, create
  155. the distribution object, sample from it, and apply some
  156. exploration logic to the results.
  157. The callable takes as inputs: Policy, ModelV2, input_dict,
  158. explore, timestep, is_training.
  159. existing_inputs: When copying a policy, this specifies an existing
  160. dict of placeholders to use instead of defining new ones.
  161. existing_model: When copying a policy, this specifies an existing
  162. model to clone and share weights with.
  163. get_batch_divisibility_req: Optional callable that returns the
  164. divisibility requirement for sample batches. If None, will
  165. assume a value of 1.
  166. """
  167. if obs_include_prev_action_reward != DEPRECATED_VALUE:
  168. deprecation_warning(old="obs_include_prev_action_reward", error=True)
  169. self.observation_space = obs_space
  170. self.action_space = action_space
  171. self.config = config
  172. self.framework = "tf"
  173. self._loss_fn = loss_fn
  174. self._stats_fn = stats_fn
  175. self._grad_stats_fn = grad_stats_fn
  176. self._seq_lens = None
  177. self._is_tower = existing_inputs is not None
  178. dist_class = None
  179. if action_sampler_fn or action_distribution_fn:
  180. if not make_model:
  181. raise ValueError(
  182. "`make_model` is required if `action_sampler_fn` OR "
  183. "`action_distribution_fn` is given"
  184. )
  185. else:
  186. dist_class, logit_dim = ModelCatalog.get_action_dist(
  187. action_space, self.config["model"]
  188. )
  189. # Setup self.model.
  190. if existing_model:
  191. if isinstance(existing_model, list):
  192. self.model = existing_model[0]
  193. # TODO: (sven) hack, but works for `target_[q_]?model`.
  194. for i in range(1, len(existing_model)):
  195. setattr(self, existing_model[i][0], existing_model[i][1])
  196. elif make_model:
  197. self.model = make_model(self, obs_space, action_space, config)
  198. else:
  199. self.model = ModelCatalog.get_model_v2(
  200. obs_space=obs_space,
  201. action_space=action_space,
  202. num_outputs=logit_dim,
  203. model_config=self.config["model"],
  204. framework="tf",
  205. )
  206. # Auto-update model's inference view requirements, if recurrent.
  207. self._update_model_view_requirements_from_init_state()
  208. # Input placeholders already given -> Use these.
  209. if existing_inputs:
  210. self._state_inputs = [
  211. v for k, v in existing_inputs.items() if k.startswith("state_in_")
  212. ]
  213. # Placeholder for RNN time-chunk valid lengths.
  214. if self._state_inputs:
  215. self._seq_lens = existing_inputs[SampleBatch.SEQ_LENS]
  216. # Create new input placeholders.
  217. else:
  218. self._state_inputs = [
  219. get_placeholder(
  220. space=vr.space,
  221. time_axis=not isinstance(vr.shift, int),
  222. name=k,
  223. )
  224. for k, vr in self.model.view_requirements.items()
  225. if k.startswith("state_in_")
  226. ]
  227. # Placeholder for RNN time-chunk valid lengths.
  228. if self._state_inputs:
  229. self._seq_lens = tf1.placeholder(
  230. dtype=tf.int32, shape=[None], name="seq_lens"
  231. )
  232. # Use default settings.
  233. # Add NEXT_OBS, STATE_IN_0.., and others.
  234. self.view_requirements = self._get_default_view_requirements()
  235. # Combine view_requirements for Model and Policy.
  236. self.view_requirements.update(self.model.view_requirements)
  237. # Disable env-info placeholder.
  238. if SampleBatch.INFOS in self.view_requirements:
  239. self.view_requirements[SampleBatch.INFOS].used_for_training = False
  240. # Setup standard placeholders.
  241. if self._is_tower:
  242. timestep = existing_inputs["timestep"]
  243. explore = False
  244. self._input_dict, self._dummy_batch = self._get_input_dict_and_dummy_batch(
  245. self.view_requirements, existing_inputs
  246. )
  247. else:
  248. if not self.config.get("_disable_action_flattening"):
  249. action_ph = ModelCatalog.get_action_placeholder(action_space)
  250. prev_action_ph = {}
  251. if SampleBatch.PREV_ACTIONS not in self.view_requirements:
  252. prev_action_ph = {
  253. SampleBatch.PREV_ACTIONS: ModelCatalog.get_action_placeholder(
  254. action_space, "prev_action"
  255. )
  256. }
  257. (
  258. self._input_dict,
  259. self._dummy_batch,
  260. ) = self._get_input_dict_and_dummy_batch(
  261. self.view_requirements,
  262. dict({SampleBatch.ACTIONS: action_ph}, **prev_action_ph),
  263. )
  264. else:
  265. (
  266. self._input_dict,
  267. self._dummy_batch,
  268. ) = self._get_input_dict_and_dummy_batch(self.view_requirements, {})
  269. # Placeholder for (sampling steps) timestep (int).
  270. timestep = tf1.placeholder_with_default(
  271. tf.zeros((), dtype=tf.int64), (), name="timestep"
  272. )
  273. # Placeholder for `is_exploring` flag.
  274. explore = tf1.placeholder_with_default(True, (), name="is_exploring")
  275. # Placeholder for `is_training` flag.
  276. self._input_dict.set_training(self._get_is_training_placeholder())
  277. # Multi-GPU towers do not need any action computing/exploration
  278. # graphs.
  279. sampled_action = None
  280. sampled_action_logp = None
  281. dist_inputs = None
  282. extra_action_fetches = {}
  283. self._state_out = None
  284. if not self._is_tower:
  285. # Create the Exploration object to use for this Policy.
  286. self.exploration = self._create_exploration()
  287. # Fully customized action generation (e.g., custom policy).
  288. if action_sampler_fn:
  289. action_sampler_outputs = action_sampler_fn(
  290. self,
  291. self.model,
  292. obs_batch=self._input_dict[SampleBatch.CUR_OBS],
  293. state_batches=self._state_inputs,
  294. seq_lens=self._seq_lens,
  295. prev_action_batch=self._input_dict.get(SampleBatch.PREV_ACTIONS),
  296. prev_reward_batch=self._input_dict.get(SampleBatch.PREV_REWARDS),
  297. explore=explore,
  298. is_training=self._input_dict.is_training,
  299. )
  300. if len(action_sampler_outputs) == 4:
  301. (
  302. sampled_action,
  303. sampled_action_logp,
  304. dist_inputs,
  305. self._state_out,
  306. ) = action_sampler_outputs
  307. else:
  308. dist_inputs = None
  309. self._state_out = []
  310. sampled_action, sampled_action_logp = action_sampler_outputs
  311. # Distribution generation is customized, e.g., DQN, DDPG.
  312. else:
  313. if action_distribution_fn:
  314. # Try new action_distribution_fn signature, supporting
  315. # state_batches and seq_lens.
  316. in_dict = self._input_dict
  317. try:
  318. (
  319. dist_inputs,
  320. dist_class,
  321. self._state_out,
  322. ) = action_distribution_fn(
  323. self,
  324. self.model,
  325. input_dict=in_dict,
  326. state_batches=self._state_inputs,
  327. seq_lens=self._seq_lens,
  328. explore=explore,
  329. timestep=timestep,
  330. is_training=in_dict.is_training,
  331. )
  332. # Trying the old way (to stay backward compatible).
  333. # TODO: Remove in future.
  334. except TypeError as e:
  335. if (
  336. "positional argument" in e.args[0]
  337. or "unexpected keyword argument" in e.args[0]
  338. ):
  339. (
  340. dist_inputs,
  341. dist_class,
  342. self._state_out,
  343. ) = action_distribution_fn(
  344. self,
  345. self.model,
  346. obs_batch=in_dict[SampleBatch.CUR_OBS],
  347. state_batches=self._state_inputs,
  348. seq_lens=self._seq_lens,
  349. prev_action_batch=in_dict.get(SampleBatch.PREV_ACTIONS),
  350. prev_reward_batch=in_dict.get(SampleBatch.PREV_REWARDS),
  351. explore=explore,
  352. is_training=in_dict.is_training,
  353. )
  354. else:
  355. raise e
  356. # Default distribution generation behavior:
  357. # Pass through model. E.g., PG, PPO.
  358. else:
  359. if isinstance(self.model, tf.keras.Model):
  360. dist_inputs, self._state_out, extra_action_fetches = self.model(
  361. self._input_dict
  362. )
  363. else:
  364. dist_inputs, self._state_out = self.model(self._input_dict)
  365. action_dist = dist_class(dist_inputs, self.model)
  366. # Using exploration to get final action (e.g. via sampling).
  367. (
  368. sampled_action,
  369. sampled_action_logp,
  370. ) = self.exploration.get_exploration_action(
  371. action_distribution=action_dist, timestep=timestep, explore=explore
  372. )
  373. if dist_inputs is not None:
  374. extra_action_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs
  375. if sampled_action_logp is not None:
  376. extra_action_fetches[SampleBatch.ACTION_LOGP] = sampled_action_logp
  377. extra_action_fetches[SampleBatch.ACTION_PROB] = tf.exp(
  378. tf.cast(sampled_action_logp, tf.float32)
  379. )
  380. # Phase 1 init.
  381. sess = tf1.get_default_session() or tf1.Session(
  382. config=tf1.ConfigProto(**self.config["tf_session_args"])
  383. )
  384. batch_divisibility_req = (
  385. get_batch_divisibility_req(self)
  386. if callable(get_batch_divisibility_req)
  387. else (get_batch_divisibility_req or 1)
  388. )
  389. prev_action_input = (
  390. self._input_dict[SampleBatch.PREV_ACTIONS]
  391. if SampleBatch.PREV_ACTIONS in self._input_dict.accessed_keys
  392. else None
  393. )
  394. prev_reward_input = (
  395. self._input_dict[SampleBatch.PREV_REWARDS]
  396. if SampleBatch.PREV_REWARDS in self._input_dict.accessed_keys
  397. else None
  398. )
  399. super().__init__(
  400. observation_space=obs_space,
  401. action_space=action_space,
  402. config=config,
  403. sess=sess,
  404. obs_input=self._input_dict[SampleBatch.OBS],
  405. action_input=self._input_dict[SampleBatch.ACTIONS],
  406. sampled_action=sampled_action,
  407. sampled_action_logp=sampled_action_logp,
  408. dist_inputs=dist_inputs,
  409. dist_class=dist_class,
  410. loss=None, # dynamically initialized on run
  411. loss_inputs=[],
  412. model=self.model,
  413. state_inputs=self._state_inputs,
  414. state_outputs=self._state_out,
  415. prev_action_input=prev_action_input,
  416. prev_reward_input=prev_reward_input,
  417. seq_lens=self._seq_lens,
  418. max_seq_len=config["model"]["max_seq_len"],
  419. batch_divisibility_req=batch_divisibility_req,
  420. explore=explore,
  421. timestep=timestep,
  422. )
  423. # Phase 2 init.
  424. if before_loss_init is not None:
  425. before_loss_init(self, obs_space, action_space, config)
  426. if hasattr(self, "_extra_action_fetches"):
  427. self._extra_action_fetches.update(extra_action_fetches)
  428. else:
  429. self._extra_action_fetches = extra_action_fetches
  430. # Loss initialization and model/postprocessing test calls.
  431. if not self._is_tower:
  432. self._initialize_loss_from_dummy_batch(auto_remove_unneeded_view_reqs=True)
  433. # Create MultiGPUTowerStacks, if we have at least one actual
  434. # GPU or >1 CPUs (fake GPUs).
  435. if len(self.devices) > 1 or any("gpu" in d for d in self.devices):
  436. # Per-GPU graph copies created here must share vars with the
  437. # policy. Therefore, `reuse` is set to tf1.AUTO_REUSE because
  438. # Adam nodes are created after all of the device copies are
  439. # created.
  440. with tf1.variable_scope("", reuse=tf1.AUTO_REUSE):
  441. self.multi_gpu_tower_stacks = [
  442. TFMultiGPUTowerStack(policy=self)
  443. for i in range(self.config.get("num_multi_gpu_tower_stacks", 1))
  444. ]
  445. # Initialize again after loss and tower init.
  446. self.get_session().run(tf1.global_variables_initializer())
  447. @override(TFPolicy)
  448. def copy(self, existing_inputs: List[Tuple[str, "tf1.placeholder"]]) -> TFPolicy:
  449. """Creates a copy of self using existing input placeholders."""
  450. flat_loss_inputs = tree.flatten(self._loss_input_dict)
  451. flat_loss_inputs_no_rnn = tree.flatten(self._loss_input_dict_no_rnn)
  452. # Note that there might be RNN state inputs at the end of the list
  453. if len(flat_loss_inputs) != len(existing_inputs):
  454. raise ValueError(
  455. "Tensor list mismatch",
  456. self._loss_input_dict,
  457. self._state_inputs,
  458. existing_inputs,
  459. )
  460. for i, v in enumerate(flat_loss_inputs_no_rnn):
  461. if v.shape.as_list() != existing_inputs[i].shape.as_list():
  462. raise ValueError(
  463. "Tensor shape mismatch", i, v.shape, existing_inputs[i].shape
  464. )
  465. # By convention, the loss inputs are followed by state inputs and then
  466. # the seq len tensor.
  467. rnn_inputs = []
  468. for i in range(len(self._state_inputs)):
  469. rnn_inputs.append(
  470. (
  471. "state_in_{}".format(i),
  472. existing_inputs[len(flat_loss_inputs_no_rnn) + i],
  473. )
  474. )
  475. if rnn_inputs:
  476. rnn_inputs.append((SampleBatch.SEQ_LENS, existing_inputs[-1]))
  477. existing_inputs_unflattened = tree.unflatten_as(
  478. self._loss_input_dict_no_rnn,
  479. existing_inputs[: len(flat_loss_inputs_no_rnn)],
  480. )
  481. input_dict = OrderedDict(
  482. [("is_exploring", self._is_exploring), ("timestep", self._timestep)]
  483. + [
  484. (k, existing_inputs_unflattened[k])
  485. for i, k in enumerate(self._loss_input_dict_no_rnn.keys())
  486. ]
  487. + rnn_inputs
  488. )
  489. instance = self.__class__(
  490. self.observation_space,
  491. self.action_space,
  492. self.config,
  493. existing_inputs=input_dict,
  494. existing_model=[
  495. self.model,
  496. # Deprecated: Target models should all reside under
  497. # `policy.target_model` now.
  498. ("target_q_model", getattr(self, "target_q_model", None)),
  499. ("target_model", getattr(self, "target_model", None)),
  500. ],
  501. )
  502. instance._loss_input_dict = input_dict
  503. losses = instance._do_loss_init(SampleBatch(input_dict))
  504. loss_inputs = [
  505. (k, existing_inputs_unflattened[k])
  506. for i, k in enumerate(self._loss_input_dict_no_rnn.keys())
  507. ]
  508. TFPolicy._initialize_loss(instance, losses, loss_inputs)
  509. if instance._grad_stats_fn:
  510. instance._stats_fetches.update(
  511. instance._grad_stats_fn(instance, input_dict, instance._grads)
  512. )
  513. return instance
  514. @override(Policy)
  515. def get_initial_state(self) -> List[TensorType]:
  516. if self.model:
  517. return self.model.get_initial_state()
  518. else:
  519. return []
  520. @override(Policy)
  521. def load_batch_into_buffer(
  522. self,
  523. batch: SampleBatch,
  524. buffer_index: int = 0,
  525. ) -> int:
  526. # Set the is_training flag of the batch.
  527. batch.set_training(True)
  528. # Shortcut for 1 CPU only: Store batch in
  529. # `self._loaded_single_cpu_batch`.
  530. if len(self.devices) == 1 and self.devices[0] == "/cpu:0":
  531. assert buffer_index == 0
  532. self._loaded_single_cpu_batch = batch
  533. return len(batch)
  534. input_dict = self._get_loss_inputs_dict(batch, shuffle=False)
  535. data_keys = tree.flatten(self._loss_input_dict_no_rnn)
  536. if self._state_inputs:
  537. state_keys = self._state_inputs + [self._seq_lens]
  538. else:
  539. state_keys = []
  540. inputs = [input_dict[k] for k in data_keys]
  541. state_inputs = [input_dict[k] for k in state_keys]
  542. return self.multi_gpu_tower_stacks[buffer_index].load_data(
  543. sess=self.get_session(),
  544. inputs=inputs,
  545. state_inputs=state_inputs,
  546. num_grad_updates=batch.num_grad_updates,
  547. )
  548. @override(Policy)
  549. def get_num_samples_loaded_into_buffer(self, buffer_index: int = 0) -> int:
  550. # Shortcut for 1 CPU only: Batch should already be stored in
  551. # `self._loaded_single_cpu_batch`.
  552. if len(self.devices) == 1 and self.devices[0] == "/cpu:0":
  553. assert buffer_index == 0
  554. return (
  555. len(self._loaded_single_cpu_batch)
  556. if self._loaded_single_cpu_batch is not None
  557. else 0
  558. )
  559. return self.multi_gpu_tower_stacks[buffer_index].num_tuples_loaded
  560. @override(Policy)
  561. def learn_on_loaded_batch(self, offset: int = 0, buffer_index: int = 0):
  562. # Shortcut for 1 CPU only: Batch should already be stored in
  563. # `self._loaded_single_cpu_batch`.
  564. if len(self.devices) == 1 and self.devices[0] == "/cpu:0":
  565. assert buffer_index == 0
  566. if self._loaded_single_cpu_batch is None:
  567. raise ValueError(
  568. "Must call Policy.load_batch_into_buffer() before "
  569. "Policy.learn_on_loaded_batch()!"
  570. )
  571. # Get the correct slice of the already loaded batch to use,
  572. # based on offset and batch size.
  573. batch_size = self.config.get("minibatch_size")
  574. if batch_size is None:
  575. batch_size = self.config.get(
  576. "sgd_minibatch_size", self.config["train_batch_size"]
  577. )
  578. if batch_size >= len(self._loaded_single_cpu_batch):
  579. sliced_batch = self._loaded_single_cpu_batch
  580. else:
  581. sliced_batch = self._loaded_single_cpu_batch.slice(
  582. start=offset, end=offset + batch_size
  583. )
  584. return self.learn_on_batch(sliced_batch)
  585. tower_stack = self.multi_gpu_tower_stacks[buffer_index]
  586. results = tower_stack.optimize(self.get_session(), offset)
  587. self.num_grad_updates += 1
  588. results.update(
  589. {
  590. NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates,
  591. # -1, b/c we have to measure this diff before we do the update above.
  592. DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: (
  593. self.num_grad_updates - 1 - (tower_stack.num_grad_updates or 0)
  594. ),
  595. }
  596. )
  597. return results
  598. def _get_input_dict_and_dummy_batch(self, view_requirements, existing_inputs):
  599. """Creates input_dict and dummy_batch for loss initialization.
  600. Used for managing the Policy's input placeholders and for loss
  601. initialization.
  602. Input_dict: Str -> tf.placeholders, dummy_batch: str -> np.arrays.
  603. Args:
  604. view_requirements: The view requirements dict.
  605. existing_inputs (Dict[str, tf.placeholder]): A dict of already
  606. existing placeholders.
  607. Returns:
  608. Tuple[Dict[str, tf.placeholder], Dict[str, np.ndarray]]: The
  609. input_dict/dummy_batch tuple.
  610. """
  611. input_dict = {}
  612. for view_col, view_req in view_requirements.items():
  613. # Point state_in to the already existing self._state_inputs.
  614. mo = re.match(r"state_in_(\d+)", view_col)
  615. if mo is not None:
  616. input_dict[view_col] = self._state_inputs[int(mo.group(1))]
  617. # State-outs (no placeholders needed).
  618. elif view_col.startswith("state_out_"):
  619. continue
  620. # Skip action dist inputs placeholder (do later).
  621. elif view_col == SampleBatch.ACTION_DIST_INPUTS:
  622. continue
  623. # This is a tower: Input placeholders already exist.
  624. elif view_col in existing_inputs:
  625. input_dict[view_col] = existing_inputs[view_col]
  626. # All others.
  627. else:
  628. time_axis = not isinstance(view_req.shift, int)
  629. if view_req.used_for_training:
  630. # Create a +time-axis placeholder if the shift is not an
  631. # int (range or list of ints).
  632. # Do not flatten actions if action flattening disabled.
  633. if self.config.get("_disable_action_flattening") and view_col in [
  634. SampleBatch.ACTIONS,
  635. SampleBatch.PREV_ACTIONS,
  636. ]:
  637. flatten = False
  638. # Do not flatten observations if no preprocessor API used.
  639. elif (
  640. view_col in [SampleBatch.OBS, SampleBatch.NEXT_OBS]
  641. and self.config["_disable_preprocessor_api"]
  642. ):
  643. flatten = False
  644. # Flatten everything else.
  645. else:
  646. flatten = True
  647. input_dict[view_col] = get_placeholder(
  648. space=view_req.space,
  649. name=view_col,
  650. time_axis=time_axis,
  651. flatten=flatten,
  652. )
  653. dummy_batch = self._get_dummy_batch_from_view_requirements(batch_size=32)
  654. return SampleBatch(input_dict, seq_lens=self._seq_lens), dummy_batch
  655. @override(Policy)
  656. def _initialize_loss_from_dummy_batch(
  657. self, auto_remove_unneeded_view_reqs: bool = True, stats_fn=None
  658. ) -> None:
  659. # Create the optimizer/exploration optimizer here. Some initialization
  660. # steps (e.g. exploration postprocessing) may need this.
  661. if not self._optimizers:
  662. self._optimizers = force_list(self.optimizer())
  663. # Backward compatibility.
  664. self._optimizer = self._optimizers[0]
  665. # Test calls depend on variable init, so initialize model first.
  666. self.get_session().run(tf1.global_variables_initializer())
  667. # Fields that have not been accessed are not needed for action
  668. # computations -> Tag them as `used_for_compute_actions=False`.
  669. for key, view_req in self.view_requirements.items():
  670. if (
  671. not key.startswith("state_in_")
  672. and key not in self._input_dict.accessed_keys
  673. ):
  674. view_req.used_for_compute_actions = False
  675. for key, value in self._extra_action_fetches.items():
  676. self._dummy_batch[key] = get_dummy_batch_for_space(
  677. gym.spaces.Box(
  678. -1.0, 1.0, shape=value.shape.as_list()[1:], dtype=value.dtype.name
  679. ),
  680. batch_size=len(self._dummy_batch),
  681. )
  682. self._input_dict[key] = get_placeholder(value=value, name=key)
  683. if key not in self.view_requirements:
  684. logger.info("Adding extra-action-fetch `{}` to view-reqs.".format(key))
  685. self.view_requirements[key] = ViewRequirement(
  686. space=gym.spaces.Box(
  687. -1.0,
  688. 1.0,
  689. shape=value.shape.as_list()[1:],
  690. dtype=value.dtype.name,
  691. ),
  692. used_for_compute_actions=False,
  693. )
  694. dummy_batch = self._dummy_batch
  695. logger.info("Testing `postprocess_trajectory` w/ dummy batch.")
  696. self.exploration.postprocess_trajectory(self, dummy_batch, self.get_session())
  697. _ = self.postprocess_trajectory(dummy_batch)
  698. # Add new columns automatically to (loss) input_dict.
  699. for key in dummy_batch.added_keys:
  700. if key not in self._input_dict:
  701. self._input_dict[key] = get_placeholder(
  702. value=dummy_batch[key], name=key
  703. )
  704. if key not in self.view_requirements:
  705. self.view_requirements[key] = ViewRequirement(
  706. space=gym.spaces.Box(
  707. -1.0,
  708. 1.0,
  709. shape=dummy_batch[key].shape[1:],
  710. dtype=dummy_batch[key].dtype,
  711. ),
  712. used_for_compute_actions=False,
  713. )
  714. train_batch = SampleBatch(
  715. dict(self._input_dict, **self._loss_input_dict),
  716. _is_training=True,
  717. )
  718. if self._state_inputs:
  719. train_batch[SampleBatch.SEQ_LENS] = self._seq_lens
  720. self._loss_input_dict.update(
  721. {SampleBatch.SEQ_LENS: train_batch[SampleBatch.SEQ_LENS]}
  722. )
  723. self._loss_input_dict.update(dict(train_batch))
  724. if log_once("loss_init"):
  725. logger.debug(
  726. "Initializing loss function with dummy input:\n\n{}\n".format(
  727. summarize(train_batch)
  728. )
  729. )
  730. losses = self._do_loss_init(train_batch)
  731. all_accessed_keys = (
  732. train_batch.accessed_keys
  733. | dummy_batch.accessed_keys
  734. | dummy_batch.added_keys
  735. | set(self.model.view_requirements.keys())
  736. )
  737. TFPolicy._initialize_loss(
  738. self,
  739. losses,
  740. [(k, v) for k, v in train_batch.items() if k in all_accessed_keys]
  741. + (
  742. [(SampleBatch.SEQ_LENS, train_batch[SampleBatch.SEQ_LENS])]
  743. if SampleBatch.SEQ_LENS in train_batch
  744. else []
  745. ),
  746. )
  747. if "is_training" in self._loss_input_dict:
  748. del self._loss_input_dict["is_training"]
  749. # Call the grads stats fn.
  750. # TODO: (sven) rename to simply stats_fn to match eager and torch.
  751. if self._grad_stats_fn:
  752. self._stats_fetches.update(
  753. self._grad_stats_fn(self, train_batch, self._grads)
  754. )
  755. # Add new columns automatically to view-reqs.
  756. if auto_remove_unneeded_view_reqs:
  757. # Add those needed for postprocessing and training.
  758. all_accessed_keys = train_batch.accessed_keys | dummy_batch.accessed_keys
  759. # Tag those only needed for post-processing (with some exceptions).
  760. for key in dummy_batch.accessed_keys:
  761. if (
  762. key not in train_batch.accessed_keys
  763. and key not in self.model.view_requirements
  764. and key
  765. not in [
  766. SampleBatch.EPS_ID,
  767. SampleBatch.AGENT_INDEX,
  768. SampleBatch.UNROLL_ID,
  769. SampleBatch.TERMINATEDS,
  770. SampleBatch.TRUNCATEDS,
  771. SampleBatch.REWARDS,
  772. SampleBatch.INFOS,
  773. SampleBatch.T,
  774. SampleBatch.OBS_EMBEDS,
  775. ]
  776. ):
  777. if key in self.view_requirements:
  778. self.view_requirements[key].used_for_training = False
  779. if key in self._loss_input_dict:
  780. del self._loss_input_dict[key]
  781. # Remove those not needed at all (leave those that are needed
  782. # by Sampler to properly execute sample collection).
  783. # Also always leave TERMINATEDS, TRUNCATEDS, REWARDS, and INFOS,
  784. # no matter what.
  785. for key in list(self.view_requirements.keys()):
  786. if (
  787. key not in all_accessed_keys
  788. and key
  789. not in [
  790. SampleBatch.EPS_ID,
  791. SampleBatch.AGENT_INDEX,
  792. SampleBatch.UNROLL_ID,
  793. SampleBatch.TERMINATEDS,
  794. SampleBatch.TRUNCATEDS,
  795. SampleBatch.REWARDS,
  796. SampleBatch.INFOS,
  797. SampleBatch.T,
  798. ]
  799. and key not in self.model.view_requirements
  800. ):
  801. # If user deleted this key manually in postprocessing
  802. # fn, warn about it and do not remove from
  803. # view-requirements.
  804. if key in dummy_batch.deleted_keys:
  805. logger.warning(
  806. "SampleBatch key '{}' was deleted manually in "
  807. "postprocessing function! RLlib will "
  808. "automatically remove non-used items from the "
  809. "data stream. Remove the `del` from your "
  810. "postprocessing function.".format(key)
  811. )
  812. # If we are not writing output to disk, safe to erase
  813. # this key to save space in the sample batch.
  814. elif self.config["output"] is None:
  815. del self.view_requirements[key]
  816. if key in self._loss_input_dict:
  817. del self._loss_input_dict[key]
  818. # Add those data_cols (again) that are missing and have
  819. # dependencies by view_cols.
  820. for key in list(self.view_requirements.keys()):
  821. vr = self.view_requirements[key]
  822. if (
  823. vr.data_col is not None
  824. and vr.data_col not in self.view_requirements
  825. ):
  826. used_for_training = vr.data_col in train_batch.accessed_keys
  827. self.view_requirements[vr.data_col] = ViewRequirement(
  828. space=vr.space, used_for_training=used_for_training
  829. )
  830. self._loss_input_dict_no_rnn = {
  831. k: v
  832. for k, v in self._loss_input_dict.items()
  833. if (v not in self._state_inputs and v != self._seq_lens)
  834. }
  835. def _do_loss_init(self, train_batch: SampleBatch):
  836. losses = self._loss_fn(self, self.model, self.dist_class, train_batch)
  837. losses = force_list(losses)
  838. if self._stats_fn:
  839. self._stats_fetches.update(self._stats_fn(self, train_batch))
  840. # Override the update ops to be those of the model.
  841. self._update_ops = []
  842. if not isinstance(self.model, tf.keras.Model):
  843. self._update_ops = self.model.update_ops()
  844. return losses
  845. @OldAPIStack
  846. class TFMultiGPUTowerStack:
  847. """Optimizer that runs in parallel across multiple local devices.
  848. TFMultiGPUTowerStack automatically splits up and loads training data
  849. onto specified local devices (e.g. GPUs) with `load_data()`. During a call
  850. to `optimize()`, the devices compute gradients over slices of the data in
  851. parallel. The gradients are then averaged and applied to the shared
  852. weights.
  853. The data loaded is pinned in device memory until the next call to
  854. `load_data`, so you can make multiple passes (possibly in randomized order)
  855. over the same data once loaded.
  856. This is similar to tf1.train.SyncReplicasOptimizer, but works within a
  857. single TensorFlow graph, i.e. implements in-graph replicated training:
  858. https://www.tensorflow.org/api_docs/python/tf/train/SyncReplicasOptimizer
  859. """
  860. def __init__(
  861. self,
  862. # Deprecated.
  863. optimizer=None,
  864. devices=None,
  865. input_placeholders=None,
  866. rnn_inputs=None,
  867. max_per_device_batch_size=None,
  868. build_graph=None,
  869. grad_norm_clipping=None,
  870. # Use only `policy` argument from here on.
  871. policy: TFPolicy = None,
  872. ):
  873. """Initializes a TFMultiGPUTowerStack instance.
  874. Args:
  875. policy: The TFPolicy object that this tower stack
  876. belongs to.
  877. """
  878. # Obsoleted usage, use only `policy` arg from here on.
  879. if policy is None:
  880. deprecation_warning(
  881. old="TFMultiGPUTowerStack(...)",
  882. new="TFMultiGPUTowerStack(policy=[Policy])",
  883. error=True,
  884. )
  885. self.policy = None
  886. self.optimizers = optimizer
  887. self.devices = devices
  888. self.max_per_device_batch_size = max_per_device_batch_size
  889. self.policy_copy = build_graph
  890. else:
  891. self.policy: TFPolicy = policy
  892. self.optimizers: List[LocalOptimizer] = self.policy._optimizers
  893. self.devices = self.policy.devices
  894. self.max_per_device_batch_size = (
  895. max_per_device_batch_size
  896. or policy.config.get(
  897. "minibatch_size", policy.config.get("train_batch_size", 999999)
  898. )
  899. ) // len(self.devices)
  900. input_placeholders = tree.flatten(self.policy._loss_input_dict_no_rnn)
  901. rnn_inputs = []
  902. if self.policy._state_inputs:
  903. rnn_inputs = self.policy._state_inputs + [self.policy._seq_lens]
  904. grad_norm_clipping = self.policy.config.get("grad_clip")
  905. self.policy_copy = self.policy.copy
  906. assert len(self.devices) > 1 or "gpu" in self.devices[0]
  907. self.loss_inputs = input_placeholders + rnn_inputs
  908. shared_ops = tf1.get_collection(
  909. tf1.GraphKeys.UPDATE_OPS, scope=tf1.get_variable_scope().name
  910. )
  911. # Then setup the per-device loss graphs that use the shared weights
  912. self._batch_index = tf1.placeholder(tf.int32, name="batch_index")
  913. # Dynamic batch size, which may be shrunk if there isn't enough data
  914. self._per_device_batch_size = tf1.placeholder(
  915. tf.int32, name="per_device_batch_size"
  916. )
  917. self._loaded_per_device_batch_size = max_per_device_batch_size
  918. # When loading RNN input, we dynamically determine the max seq len
  919. self._max_seq_len = tf1.placeholder(tf.int32, name="max_seq_len")
  920. self._loaded_max_seq_len = 1
  921. device_placeholders = [[] for _ in range(len(self.devices))]
  922. for t in tree.flatten(self.loss_inputs):
  923. # Split on the CPU in case the data doesn't fit in GPU memory.
  924. with tf.device("/cpu:0"):
  925. splits = tf.split(t, len(self.devices))
  926. for i, d in enumerate(self.devices):
  927. device_placeholders[i].append(splits[i])
  928. self._towers = []
  929. for tower_i, (device, placeholders) in enumerate(
  930. zip(self.devices, device_placeholders)
  931. ):
  932. self._towers.append(
  933. self._setup_device(
  934. tower_i, device, placeholders, len(tree.flatten(input_placeholders))
  935. )
  936. )
  937. if self.policy.config["_tf_policy_handles_more_than_one_loss"]:
  938. avgs = []
  939. for i, optim in enumerate(self.optimizers):
  940. avg = _average_gradients([t.grads[i] for t in self._towers])
  941. if grad_norm_clipping:
  942. clipped = []
  943. for grad, _ in avg:
  944. clipped.append(grad)
  945. clipped, _ = tf.clip_by_global_norm(clipped, grad_norm_clipping)
  946. for i, (grad, var) in enumerate(avg):
  947. avg[i] = (clipped[i], var)
  948. avgs.append(avg)
  949. # Gather update ops for any batch norm layers.
  950. # TODO(ekl) here we
  951. # will use all the ops found which won't work for DQN / DDPG, but
  952. # those aren't supported with multi-gpu right now anyways.
  953. self._update_ops = tf1.get_collection(
  954. tf1.GraphKeys.UPDATE_OPS, scope=tf1.get_variable_scope().name
  955. )
  956. for op in shared_ops:
  957. self._update_ops.remove(op) # only care about tower update ops
  958. if self._update_ops:
  959. logger.debug(
  960. "Update ops to run on apply gradient: {}".format(self._update_ops)
  961. )
  962. with tf1.control_dependencies(self._update_ops):
  963. self._train_op = tf.group(
  964. [o.apply_gradients(a) for o, a in zip(self.optimizers, avgs)]
  965. )
  966. else:
  967. avg = _average_gradients([t.grads for t in self._towers])
  968. if grad_norm_clipping:
  969. clipped = []
  970. for grad, _ in avg:
  971. clipped.append(grad)
  972. clipped, _ = tf.clip_by_global_norm(clipped, grad_norm_clipping)
  973. for i, (grad, var) in enumerate(avg):
  974. avg[i] = (clipped[i], var)
  975. # Gather update ops for any batch norm layers.
  976. # TODO(ekl) here we
  977. # will use all the ops found which won't work for DQN / DDPG, but
  978. # those aren't supported with multi-gpu right now anyways.
  979. self._update_ops = tf1.get_collection(
  980. tf1.GraphKeys.UPDATE_OPS, scope=tf1.get_variable_scope().name
  981. )
  982. for op in shared_ops:
  983. self._update_ops.remove(op) # only care about tower update ops
  984. if self._update_ops:
  985. logger.debug(
  986. "Update ops to run on apply gradient: {}".format(self._update_ops)
  987. )
  988. with tf1.control_dependencies(self._update_ops):
  989. self._train_op = self.optimizers[0].apply_gradients(avg)
  990. # The lifetime number of gradient updates that the policy having sent
  991. # some data (SampleBatchType) into this tower stack's GPU buffer(s) has already
  992. # undergone.
  993. self.num_grad_updates = 0
  994. def load_data(self, sess, inputs, state_inputs, num_grad_updates=None):
  995. """Bulk loads the specified inputs into device memory.
  996. The shape of the inputs must conform to the shapes of the input
  997. placeholders this optimizer was constructed with.
  998. The data is split equally across all the devices. If the data is not
  999. evenly divisible by the batch size, excess data will be discarded.
  1000. Args:
  1001. sess: TensorFlow session.
  1002. inputs: List of arrays matching the input placeholders, of shape
  1003. [BATCH_SIZE, ...].
  1004. state_inputs: List of RNN input arrays. These arrays have size
  1005. [BATCH_SIZE / MAX_SEQ_LEN, ...].
  1006. num_grad_updates: The lifetime number of gradient updates that the
  1007. policy having collected the data has already undergone.
  1008. Returns:
  1009. The number of tuples loaded per device.
  1010. """
  1011. self.num_grad_updates = num_grad_updates
  1012. if log_once("load_data"):
  1013. logger.info(
  1014. "Training on concatenated sample batches:\n\n{}\n".format(
  1015. summarize(
  1016. {
  1017. "placeholders": self.loss_inputs,
  1018. "inputs": inputs,
  1019. "state_inputs": state_inputs,
  1020. }
  1021. )
  1022. )
  1023. )
  1024. feed_dict = {}
  1025. assert len(self.loss_inputs) == len(inputs + state_inputs), (
  1026. self.loss_inputs,
  1027. inputs,
  1028. state_inputs,
  1029. )
  1030. # Let's suppose we have the following input data, and 2 devices:
  1031. # 1 2 3 4 5 6 7 <- state inputs shape
  1032. # A A A B B B C C C D D D E E E F F F G G G <- inputs shape
  1033. # The data is truncated and split across devices as follows:
  1034. # |---| seq len = 3
  1035. # |---------------------------------| seq batch size = 6 seqs
  1036. # |----------------| per device batch size = 9 tuples
  1037. if len(state_inputs) > 0:
  1038. smallest_array = state_inputs[0]
  1039. seq_len = len(inputs[0]) // len(state_inputs[0])
  1040. self._loaded_max_seq_len = seq_len
  1041. else:
  1042. smallest_array = inputs[0]
  1043. self._loaded_max_seq_len = 1
  1044. sequences_per_minibatch = (
  1045. self.max_per_device_batch_size
  1046. // self._loaded_max_seq_len
  1047. * len(self.devices)
  1048. )
  1049. if sequences_per_minibatch < 1:
  1050. logger.warning(
  1051. (
  1052. "Target minibatch size is {}, however the rollout sequence "
  1053. "length is {}, hence the minibatch size will be raised to "
  1054. "{}."
  1055. ).format(
  1056. self.max_per_device_batch_size,
  1057. self._loaded_max_seq_len,
  1058. self._loaded_max_seq_len * len(self.devices),
  1059. )
  1060. )
  1061. sequences_per_minibatch = 1
  1062. if len(smallest_array) < sequences_per_minibatch:
  1063. # Dynamically shrink the batch size if insufficient data
  1064. sequences_per_minibatch = _make_divisible_by(
  1065. len(smallest_array), len(self.devices)
  1066. )
  1067. if log_once("data_slicing"):
  1068. logger.info(
  1069. (
  1070. "Divided {} rollout sequences, each of length {}, among "
  1071. "{} devices."
  1072. ).format(
  1073. len(smallest_array), self._loaded_max_seq_len, len(self.devices)
  1074. )
  1075. )
  1076. if sequences_per_minibatch < len(self.devices):
  1077. raise ValueError(
  1078. "Must load at least 1 tuple sequence per device. Try "
  1079. "increasing `minibatch_size` or reducing `max_seq_len` "
  1080. "to ensure that at least one sequence fits per device."
  1081. )
  1082. self._loaded_per_device_batch_size = (
  1083. sequences_per_minibatch // len(self.devices) * self._loaded_max_seq_len
  1084. )
  1085. if len(state_inputs) > 0:
  1086. # First truncate the RNN state arrays to the sequences_per_minib.
  1087. state_inputs = [
  1088. _make_divisible_by(arr, sequences_per_minibatch) for arr in state_inputs
  1089. ]
  1090. # Then truncate the data inputs to match
  1091. inputs = [arr[: len(state_inputs[0]) * seq_len] for arr in inputs]
  1092. assert len(state_inputs[0]) * seq_len == len(inputs[0]), (
  1093. len(state_inputs[0]),
  1094. sequences_per_minibatch,
  1095. seq_len,
  1096. len(inputs[0]),
  1097. )
  1098. for ph, arr in zip(self.loss_inputs, inputs + state_inputs):
  1099. feed_dict[ph] = arr
  1100. truncated_len = len(inputs[0])
  1101. else:
  1102. truncated_len = 0
  1103. for ph, arr in zip(self.loss_inputs, inputs):
  1104. truncated_arr = _make_divisible_by(arr, sequences_per_minibatch)
  1105. feed_dict[ph] = truncated_arr
  1106. if truncated_len == 0:
  1107. truncated_len = len(truncated_arr)
  1108. sess.run([t.init_op for t in self._towers], feed_dict=feed_dict)
  1109. self.num_tuples_loaded = truncated_len
  1110. samples_per_device = truncated_len // len(self.devices)
  1111. assert samples_per_device > 0, "No data loaded?"
  1112. assert samples_per_device % self._loaded_per_device_batch_size == 0
  1113. # Return loaded samples per-device.
  1114. return samples_per_device
  1115. def optimize(self, sess, batch_index):
  1116. """Run a single step of SGD.
  1117. Runs a SGD step over a slice of the preloaded batch with size given by
  1118. self._loaded_per_device_batch_size and offset given by the batch_index
  1119. argument.
  1120. Updates shared model weights based on the averaged per-device
  1121. gradients.
  1122. Args:
  1123. sess: TensorFlow session.
  1124. batch_index: Offset into the preloaded data. This value must be
  1125. between `0` and `tuples_per_device`. The amount of data to
  1126. process is at most `max_per_device_batch_size`.
  1127. Returns:
  1128. The outputs of extra_ops evaluated over the batch.
  1129. """
  1130. feed_dict = {
  1131. self._batch_index: batch_index,
  1132. self._per_device_batch_size: self._loaded_per_device_batch_size,
  1133. self._max_seq_len: self._loaded_max_seq_len,
  1134. }
  1135. for tower in self._towers:
  1136. feed_dict.update(tower.loss_graph.extra_compute_grad_feed_dict())
  1137. fetches = {"train": self._train_op}
  1138. for tower_num, tower in enumerate(self._towers):
  1139. tower_fetch = tower.loss_graph._get_grad_and_stats_fetches()
  1140. fetches["tower_{}".format(tower_num)] = tower_fetch
  1141. return sess.run(fetches, feed_dict=feed_dict)
  1142. def get_device_losses(self):
  1143. return [t.loss_graph for t in self._towers]
  1144. def _setup_device(self, tower_i, device, device_input_placeholders, num_data_in):
  1145. assert num_data_in <= len(device_input_placeholders)
  1146. with tf.device(device):
  1147. with tf1.name_scope(TOWER_SCOPE_NAME + f"_{tower_i}"):
  1148. device_input_batches = []
  1149. device_input_slices = []
  1150. for i, ph in enumerate(device_input_placeholders):
  1151. current_batch = tf1.Variable(
  1152. ph, trainable=False, validate_shape=False, collections=[]
  1153. )
  1154. device_input_batches.append(current_batch)
  1155. if i < num_data_in:
  1156. scale = self._max_seq_len
  1157. granularity = self._max_seq_len
  1158. else:
  1159. scale = self._max_seq_len
  1160. granularity = 1
  1161. current_slice = tf.slice(
  1162. current_batch,
  1163. (
  1164. [self._batch_index // scale * granularity]
  1165. + [0] * len(ph.shape[1:])
  1166. ),
  1167. (
  1168. [self._per_device_batch_size // scale * granularity]
  1169. + [-1] * len(ph.shape[1:])
  1170. ),
  1171. )
  1172. current_slice.set_shape(ph.shape)
  1173. device_input_slices.append(current_slice)
  1174. graph_obj = self.policy_copy(device_input_slices)
  1175. device_grads = graph_obj.gradients(self.optimizers, graph_obj._losses)
  1176. return _Tower(
  1177. tf.group(*[batch.initializer for batch in device_input_batches]),
  1178. device_grads,
  1179. graph_obj,
  1180. )
  1181. # Each tower is a copy of the loss graph pinned to a specific device.
  1182. _Tower = namedtuple("Tower", ["init_op", "grads", "loss_graph"])
  1183. def _make_divisible_by(a, n):
  1184. if type(a) is int:
  1185. return a - a % n
  1186. return a[0 : a.shape[0] - a.shape[0] % n]
  1187. def _average_gradients(tower_grads):
  1188. """Averages gradients across towers.
  1189. Calculate the average gradient for each shared variable across all towers.
  1190. Note that this function provides a synchronization point across all towers.
  1191. Args:
  1192. tower_grads: List of lists of (gradient, variable) tuples. The outer
  1193. list is over individual gradients. The inner list is over the
  1194. gradient calculation for each tower.
  1195. Returns:
  1196. List of pairs of (gradient, variable) where the gradient has been
  1197. averaged across all towers.
  1198. TODO(ekl): We could use NCCL if this becomes a bottleneck.
  1199. """
  1200. average_grads = []
  1201. for grad_and_vars in zip(*tower_grads):
  1202. # Note that each grad_and_vars looks like the following:
  1203. # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
  1204. grads = []
  1205. for g, _ in grad_and_vars:
  1206. if g is not None:
  1207. # Add 0 dimension to the gradients to represent the tower.
  1208. expanded_g = tf.expand_dims(g, 0)
  1209. # Append on a 'tower' dimension which we will average over
  1210. # below.
  1211. grads.append(expanded_g)
  1212. if not grads:
  1213. continue
  1214. # Average over the 'tower' dimension.
  1215. grad = tf.concat(axis=0, values=grads)
  1216. grad = tf.reduce_mean(grad, 0)
  1217. # Keep in mind that the Variables are redundant because they are shared
  1218. # across towers. So .. we will just return the first tower's pointer to
  1219. # the Variable.
  1220. v = grad_and_vars[0][1]
  1221. grad_and_var = (grad, v)
  1222. average_grads.append(grad_and_var)
  1223. return average_grads