rnn_sequencing.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. """RNN utils for RLlib.
  2. The main trick here is that we add the time dimension at the last moment.
  3. The non-LSTM layers of the model see their inputs as one flat batch. Before
  4. the LSTM cell, we reshape the input to add the expected time dimension. During
  5. postprocessing, we dynamically pad the experience batches so that this
  6. reshaping is possible.
  7. Note that this padding strategy only works out if we assume zero inputs don't
  8. meaningfully affect the loss function. This happens to be true for all the
  9. current algorithms: https://github.com/ray-project/ray/issues/2992
  10. """
  11. import logging
  12. import numpy as np
  13. import tree # pip install dm_tree
  14. from typing import List, Optional
  15. from ray.rllib.policy.sample_batch import SampleBatch
  16. from ray.rllib.utils.annotations import DeveloperAPI
  17. from ray.rllib.utils.debug import summarize
  18. from ray.rllib.utils.framework import try_import_tf, try_import_torch
  19. from ray.rllib.utils.typing import TensorType, ViewRequirementsDict
  20. from ray.util import log_once
  21. tf1, tf, tfv = try_import_tf()
  22. torch, _ = try_import_torch()
  23. logger = logging.getLogger(__name__)
  24. @DeveloperAPI
  25. def pad_batch_to_sequences_of_same_size(
  26. batch: SampleBatch,
  27. max_seq_len: int,
  28. shuffle: bool = False,
  29. batch_divisibility_req: int = 1,
  30. feature_keys: Optional[List[str]] = None,
  31. view_requirements: Optional[ViewRequirementsDict] = None,
  32. ):
  33. """Applies padding to `batch` so it's choppable into same-size sequences.
  34. Shuffles `batch` (if desired), makes sure divisibility requirement is met,
  35. then pads the batch ([B, ...]) into same-size chunks ([B, ...]) w/o
  36. adding a time dimension (yet).
  37. Padding depends on episodes found in batch and `max_seq_len`.
  38. Args:
  39. batch: The SampleBatch object. All values in here have
  40. the shape [B, ...].
  41. max_seq_len: The max. sequence length to use for chopping.
  42. shuffle: Whether to shuffle batch sequences. Shuffle may
  43. be done in-place. This only makes sense if you're further
  44. applying minibatch SGD after getting the outputs.
  45. batch_divisibility_req: The int by which the batch dimension
  46. must be dividable.
  47. feature_keys: An optional list of keys to apply sequence-chopping
  48. to. If None, use all keys in batch that are not
  49. "state_in/out_"-type keys.
  50. view_requirements: An optional Policy ViewRequirements dict to
  51. be able to infer whether e.g. dynamic max'ing should be
  52. applied over the seq_lens.
  53. """
  54. # If already zero-padded, skip.
  55. if batch.zero_padded:
  56. return
  57. batch.zero_padded = True
  58. if batch_divisibility_req > 1:
  59. meets_divisibility_reqs = (
  60. len(batch[SampleBatch.CUR_OBS]) % batch_divisibility_req == 0
  61. # not multiagent
  62. and max(batch[SampleBatch.AGENT_INDEX]) == 0)
  63. else:
  64. meets_divisibility_reqs = True
  65. states_already_reduced_to_init = False
  66. # RNN/attention net case. Figure out whether we should apply dynamic
  67. # max'ing over the list of sequence lengths.
  68. if "state_in_0" in batch or "state_out_0" in batch:
  69. # Check, whether the state inputs have already been reduced to their
  70. # init values at the beginning of each max_seq_len chunk.
  71. if batch.get(SampleBatch.SEQ_LENS) is not None and \
  72. len(batch["state_in_0"]) == len(batch[SampleBatch.SEQ_LENS]):
  73. states_already_reduced_to_init = True
  74. # RNN (or single timestep state-in): Set the max dynamically.
  75. if view_requirements["state_in_0"].shift_from is None:
  76. dynamic_max = True
  77. # Attention Nets (state inputs are over some range): No dynamic maxing
  78. # possible.
  79. else:
  80. dynamic_max = False
  81. # Multi-agent case.
  82. elif not meets_divisibility_reqs:
  83. max_seq_len = batch_divisibility_req
  84. dynamic_max = False
  85. batch.max_seq_len = max_seq_len
  86. # Simple case: No RNN/attention net, nor do we need to pad.
  87. else:
  88. if shuffle:
  89. batch.shuffle()
  90. return
  91. # RNN, attention net, or multi-agent case.
  92. state_keys = []
  93. feature_keys_ = feature_keys or []
  94. for k, v in batch.items():
  95. if k.startswith("state_in_"):
  96. state_keys.append(k)
  97. elif not feature_keys and not k.startswith("state_out_") and \
  98. k not in ["infos", SampleBatch.SEQ_LENS]:
  99. feature_keys_.append(k)
  100. feature_sequences, initial_states, seq_lens = \
  101. chop_into_sequences(
  102. feature_columns=[batch[k] for k in feature_keys_],
  103. state_columns=[batch[k] for k in state_keys],
  104. episode_ids=batch.get(SampleBatch.EPS_ID),
  105. unroll_ids=batch.get(SampleBatch.UNROLL_ID),
  106. agent_indices=batch.get(SampleBatch.AGENT_INDEX),
  107. seq_lens=batch.get(SampleBatch.SEQ_LENS),
  108. max_seq_len=max_seq_len,
  109. dynamic_max=dynamic_max,
  110. states_already_reduced_to_init=states_already_reduced_to_init,
  111. shuffle=shuffle,
  112. handle_nested_data=True,
  113. )
  114. for i, k in enumerate(feature_keys_):
  115. batch[k] = tree.unflatten_as(batch[k], feature_sequences[i])
  116. for i, k in enumerate(state_keys):
  117. batch[k] = initial_states[i]
  118. batch[SampleBatch.SEQ_LENS] = np.array(seq_lens)
  119. if log_once("rnn_ma_feed_dict"):
  120. logger.info("Padded input for RNN/Attn.Nets/MA:\n\n{}\n".format(
  121. summarize({
  122. "features": feature_sequences,
  123. "initial_states": initial_states,
  124. "seq_lens": seq_lens,
  125. "max_seq_len": max_seq_len,
  126. })))
  127. @DeveloperAPI
  128. def add_time_dimension(padded_inputs: TensorType,
  129. *,
  130. max_seq_len: int,
  131. framework: str = "tf",
  132. time_major: bool = False):
  133. """Adds a time dimension to padded inputs.
  134. Args:
  135. padded_inputs (TensorType): a padded batch of sequences. That is,
  136. for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where
  137. A, B, C are sequence elements and * denotes padding.
  138. max_seq_len (int): The max. sequence length in padded_inputs.
  139. framework (str): The framework string ("tf2", "tf", "tfe", "torch").
  140. time_major (bool): Whether data should be returned in time-major (TxB)
  141. format or not (BxT).
  142. Returns:
  143. TensorType: Reshaped tensor of shape [B, T, ...] or [T, B, ...].
  144. """
  145. # Sequence lengths have to be specified for LSTM batch inputs. The
  146. # input batch must be padded to the max seq length given here. That is,
  147. # batch_size == len(seq_lens) * max(seq_lens)
  148. if framework in ["tf2", "tf", "tfe"]:
  149. assert time_major is False, "time-major not supported yet for tf!"
  150. padded_batch_size = tf.shape(padded_inputs)[0]
  151. # Dynamically reshape the padded batch to introduce a time dimension.
  152. new_batch_size = padded_batch_size // max_seq_len
  153. new_shape = (
  154. [new_batch_size, max_seq_len] + list(padded_inputs.shape[1:]))
  155. return tf.reshape(padded_inputs, new_shape)
  156. else:
  157. assert framework == "torch", "`framework` must be either tf or torch!"
  158. padded_batch_size = padded_inputs.shape[0]
  159. # Dynamically reshape the padded batch to introduce a time dimension.
  160. new_batch_size = padded_batch_size // max_seq_len
  161. if time_major:
  162. new_shape = (max_seq_len, new_batch_size) + padded_inputs.shape[1:]
  163. else:
  164. new_shape = (new_batch_size, max_seq_len) + padded_inputs.shape[1:]
  165. return torch.reshape(padded_inputs, new_shape)
  166. @DeveloperAPI
  167. def chop_into_sequences(
  168. *,
  169. feature_columns,
  170. state_columns,
  171. max_seq_len,
  172. episode_ids=None,
  173. unroll_ids=None,
  174. agent_indices=None,
  175. dynamic_max=True,
  176. shuffle=False,
  177. seq_lens=None,
  178. states_already_reduced_to_init=False,
  179. handle_nested_data=False,
  180. _extra_padding=0,
  181. ):
  182. """Truncate and pad experiences into fixed-length sequences.
  183. Args:
  184. feature_columns (list): List of arrays containing features.
  185. state_columns (list): List of arrays containing LSTM state values.
  186. max_seq_len (int): Max length of sequences before truncation.
  187. episode_ids (List[EpisodeID]): List of episode ids for each step.
  188. unroll_ids (List[UnrollID]): List of identifiers for the sample batch.
  189. This is used to make sure sequences are cut between sample batches.
  190. agent_indices (List[AgentID]): List of agent ids for each step. Note
  191. that this has to be combined with episode_ids for uniqueness.
  192. dynamic_max (bool): Whether to dynamically shrink the max seq len.
  193. For example, if max len is 20 and the actual max seq len in the
  194. data is 7, it will be shrunk to 7.
  195. shuffle (bool): Whether to shuffle the sequence outputs.
  196. handle_nested_data: If True, assume that the data in
  197. `feature_columns` could be nested structures (of data).
  198. If False, assumes that all items in `feature_columns` are
  199. only np.ndarrays (no nested structured of np.ndarrays).
  200. _extra_padding (int): Add extra padding to the end of sequences.
  201. Returns:
  202. f_pad (list): Padded feature columns. These will be of shape
  203. [NUM_SEQUENCES * MAX_SEQ_LEN, ...].
  204. s_init (list): Initial states for each sequence, of shape
  205. [NUM_SEQUENCES, ...].
  206. seq_lens (list): List of sequence lengths, of shape [NUM_SEQUENCES].
  207. Examples:
  208. >>> f_pad, s_init, seq_lens = chop_into_sequences(
  209. episode_ids=[1, 1, 5, 5, 5, 5],
  210. unroll_ids=[4, 4, 4, 4, 4, 4],
  211. agent_indices=[0, 0, 0, 0, 0, 0],
  212. feature_columns=[[4, 4, 8, 8, 8, 8],
  213. [1, 1, 0, 1, 1, 0]],
  214. state_columns=[[4, 5, 4, 5, 5, 5]],
  215. max_seq_len=3)
  216. >>> print(f_pad)
  217. [[4, 4, 0, 8, 8, 8, 8, 0, 0],
  218. [1, 1, 0, 0, 1, 1, 0, 0, 0]]
  219. >>> print(s_init)
  220. [[4, 4, 5]]
  221. >>> print(seq_lens)
  222. [2, 3, 1]
  223. """
  224. if seq_lens is None or len(seq_lens) == 0:
  225. prev_id = None
  226. seq_lens = []
  227. seq_len = 0
  228. unique_ids = np.add(
  229. np.add(episode_ids, agent_indices),
  230. np.array(unroll_ids, dtype=np.int64) << 32)
  231. for uid in unique_ids:
  232. if (prev_id is not None and uid != prev_id) or \
  233. seq_len >= max_seq_len:
  234. seq_lens.append(seq_len)
  235. seq_len = 0
  236. seq_len += 1
  237. prev_id = uid
  238. if seq_len:
  239. seq_lens.append(seq_len)
  240. seq_lens = np.array(seq_lens, dtype=np.int32)
  241. # Dynamically shrink max len as needed to optimize memory usage
  242. if dynamic_max:
  243. max_seq_len = max(seq_lens) + _extra_padding
  244. feature_sequences = []
  245. for col in feature_columns:
  246. if isinstance(col, list):
  247. col = np.array(col)
  248. feature_sequences.append([])
  249. for f in tree.flatten(col):
  250. # Save unnecessary copy.
  251. if not isinstance(f, np.ndarray):
  252. f = np.array(f)
  253. length = len(seq_lens) * max_seq_len
  254. if f.dtype == np.object or f.dtype.type is np.str_:
  255. f_pad = [None] * length
  256. else:
  257. # Make sure type doesn't change.
  258. f_pad = np.zeros((length, ) + np.shape(f)[1:], dtype=f.dtype)
  259. seq_base = 0
  260. i = 0
  261. for len_ in seq_lens:
  262. for seq_offset in range(len_):
  263. f_pad[seq_base + seq_offset] = f[i]
  264. i += 1
  265. seq_base += max_seq_len
  266. assert i == len(f), f
  267. feature_sequences[-1].append(f_pad)
  268. if states_already_reduced_to_init:
  269. initial_states = state_columns
  270. else:
  271. initial_states = []
  272. for s in state_columns:
  273. # Skip unnecessary copy.
  274. if not isinstance(s, np.ndarray):
  275. s = np.array(s)
  276. s_init = []
  277. i = 0
  278. for len_ in seq_lens:
  279. s_init.append(s[i])
  280. i += len_
  281. initial_states.append(np.array(s_init))
  282. if shuffle:
  283. permutation = np.random.permutation(len(seq_lens))
  284. for i, f in enumerate(tree.flatten(feature_sequences)):
  285. orig_shape = f.shape
  286. f = np.reshape(f, (len(seq_lens), -1) + f.shape[1:])
  287. f = f[permutation]
  288. f = np.reshape(f, orig_shape)
  289. feature_sequences[i] = f
  290. for i, s in enumerate(initial_states):
  291. s = s[permutation]
  292. initial_states[i] = s
  293. seq_lens = seq_lens[permutation]
  294. # Classic behavior: Don't assume data in feature_columns are nested
  295. # structs. Don't return them as flattened lists, but as is (index 0).
  296. if not handle_nested_data:
  297. feature_sequences = [f[0] for f in feature_sequences]
  298. return feature_sequences, initial_states, seq_lens
  299. def timeslice_along_seq_lens_with_overlap(
  300. sample_batch,
  301. seq_lens=None,
  302. zero_pad_max_seq_len=0,
  303. pre_overlap=0,
  304. zero_init_states=True) -> List["SampleBatch"]:
  305. """Slices batch along `seq_lens` (each seq-len item produces one batch).
  306. Asserts that seq_lens is given or sample_batch["seq_lens"] is not None.
  307. Args:
  308. sample_batch (SampleBatch): The SampleBatch to timeslice.
  309. seq_lens (Optional[List[int]]): An optional list of seq_lens to slice
  310. at. If None, use `sample_batch[SampleBatch.SEQ_LENS]`.
  311. zero_pad_max_seq_len (int): If >0, already zero-pad the resulting
  312. slices up to this length. NOTE: This max-len will include the
  313. additional timesteps gained via setting pre_overlap (see Example).
  314. pre_overlap (int): If >0, will overlap each two consecutive slices by
  315. this many timesteps (toward the left side). This will cause
  316. zero-padding at the very beginning of the batch.
  317. zero_init_states (bool): Whether initial states should always be
  318. zero'd. If False, will use the state_outs of the batch to
  319. populate state_in values.
  320. Returns:
  321. List[SampleBatch]: The list of (new) SampleBatches.
  322. Examples:
  323. assert seq_lens == [5, 5, 2]
  324. assert sample_batch.count == 12
  325. # self = 0 1 2 3 4 | 5 6 7 8 9 | 10 11 <- timesteps
  326. slices = timeslices_along_seq_lens(
  327. zero_pad_max_seq_len=10,
  328. pre_overlap=3)
  329. # Z = zero padding (at beginning or end).
  330. # |pre (3)| seq | max-seq-len (up to 10)
  331. # slices[0] = | Z Z Z | 0 1 2 3 4 | Z Z
  332. # slices[1] = | 2 3 4 | 5 6 7 8 9 | Z Z
  333. # slices[2] = | 7 8 9 | 10 11 Z Z Z | Z Z
  334. # Note that `zero_pad_max_seq_len=10` includes the 3 pre-overlaps
  335. # count (makes sure each slice has exactly length 10).
  336. """
  337. if seq_lens is None:
  338. seq_lens = sample_batch.get(SampleBatch.SEQ_LENS)
  339. assert seq_lens is not None and len(seq_lens) > 0, \
  340. "Cannot timeslice along `seq_lens` when `seq_lens` is empty or None!"
  341. # Generate n slices based on seq_lens.
  342. start = 0
  343. slices = []
  344. for seq_len in seq_lens:
  345. pre_begin = start - pre_overlap
  346. slice_begin = start
  347. end = start + seq_len
  348. slices.append((pre_begin, slice_begin, end))
  349. start += seq_len
  350. timeslices = []
  351. for begin, slice_begin, end in slices:
  352. zero_length = None
  353. data_begin = 0
  354. zero_init_states_ = zero_init_states
  355. if begin < 0:
  356. zero_length = pre_overlap
  357. data_begin = slice_begin
  358. zero_init_states_ = True
  359. else:
  360. eps_ids = sample_batch[SampleBatch.EPS_ID][begin if begin >= 0 else
  361. 0:end]
  362. is_last_episode_ids = eps_ids == eps_ids[-1]
  363. if not is_last_episode_ids[0]:
  364. zero_length = int(sum(1.0 - is_last_episode_ids))
  365. data_begin = begin + zero_length
  366. zero_init_states_ = True
  367. if zero_length is not None:
  368. data = {
  369. k: np.concatenate([
  370. np.zeros(
  371. shape=(zero_length, ) + v.shape[1:], dtype=v.dtype),
  372. v[data_begin:end]
  373. ])
  374. for k, v in sample_batch.items() if k != SampleBatch.SEQ_LENS
  375. }
  376. else:
  377. data = {
  378. k: v[begin:end]
  379. for k, v in sample_batch.items() if k != SampleBatch.SEQ_LENS
  380. }
  381. if zero_init_states_:
  382. i = 0
  383. key = "state_in_{}".format(i)
  384. while key in data:
  385. data[key] = np.zeros_like(sample_batch[key][0:1])
  386. # Del state_out_n from data if exists.
  387. data.pop("state_out_{}".format(i), None)
  388. i += 1
  389. key = "state_in_{}".format(i)
  390. # TODO: This will not work with attention nets as their state_outs are
  391. # not compatible with state_ins.
  392. else:
  393. i = 0
  394. key = "state_in_{}".format(i)
  395. while key in data:
  396. data[key] = sample_batch["state_out_{}".format(i)][begin -
  397. 1:begin]
  398. del data["state_out_{}".format(i)]
  399. i += 1
  400. key = "state_in_{}".format(i)
  401. timeslices.append(SampleBatch(data, seq_lens=[end - begin]))
  402. # Zero-pad each slice if necessary.
  403. if zero_pad_max_seq_len > 0:
  404. for ts in timeslices:
  405. ts.right_zero_pad(
  406. max_seq_len=zero_pad_max_seq_len, exclude_states=True)
  407. return timeslices