schedules.py 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438
  1. # mypy: allow-untyped-defs
  2. # Copyright (c) Meta Platforms, Inc. and affiliates
  3. import copy
  4. import csv
  5. import itertools
  6. import logging
  7. import re
  8. from abc import ABC, abstractmethod
  9. from collections import Counter, defaultdict
  10. from collections.abc import Callable
  11. from enum import Enum
  12. from functools import lru_cache
  13. from typing import Any, cast, NamedTuple, Protocol
  14. import torch
  15. import torch.distributed as dist
  16. from torch._dynamo import OptimizedModule
  17. from torch.distributed.fsdp import FSDPModule, UnshardHandle
  18. from torch.nn.modules.loss import _Loss
  19. from torch.profiler import record_function
  20. from ._utils import generate_rank_to_stage_mapping, generate_stage_to_rank_mapping
  21. from .microbatch import merge_chunks, split_args_kwargs_into_chunks, TensorChunkSpec
  22. from .stage import _PipelineStageBase
  23. __all__ = [
  24. "get_schedule_class",
  25. "PipelineScheduleSingle",
  26. "PipelineScheduleMulti",
  27. "Schedule1F1B",
  28. "ScheduleGPipe",
  29. "ScheduleInterleaved1F1B",
  30. "ScheduleLoopedBFS",
  31. "ScheduleInterleavedZeroBubble",
  32. "ScheduleZBVZeroBubble",
  33. "ScheduleDualPipeV",
  34. ]
  35. logger = logging.getLogger(__name__)
  36. class _ComputationType(Enum):
  37. # TODO(whc) rename to _ActType?
  38. FORWARD = 1
  39. BACKWARD_INPUT = 2
  40. BACKWARD_WEIGHT = 3
  41. UNSHARD = 4
  42. RESHARD = 5
  43. SEND_F = 6
  44. RECV_F = 7
  45. SEND_B = 8
  46. RECV_B = 9
  47. FULL_BACKWARD = 10
  48. OVERLAP_F_B = 11
  49. REDUCE_GRAD = 12
  50. def __str__(self):
  51. str_map = {
  52. _ComputationType.FORWARD: "F",
  53. _ComputationType.BACKWARD_INPUT: "I",
  54. _ComputationType.BACKWARD_WEIGHT: "W",
  55. _ComputationType.UNSHARD: "UNSHARD",
  56. _ComputationType.RESHARD: "RESHARD",
  57. _ComputationType.SEND_F: "SEND_F",
  58. _ComputationType.RECV_F: "RECV_F",
  59. _ComputationType.SEND_B: "SEND_B",
  60. _ComputationType.RECV_B: "RECV_B",
  61. _ComputationType.FULL_BACKWARD: "B",
  62. _ComputationType.OVERLAP_F_B: "OVERLAP_F_B",
  63. _ComputationType.REDUCE_GRAD: "REDUCE_GRAD",
  64. }
  65. return str_map[self]
  66. @staticmethod
  67. def from_str(action):
  68. if action == "F":
  69. return _ComputationType.FORWARD
  70. elif action == "I":
  71. return _ComputationType.BACKWARD_INPUT
  72. elif action == "W":
  73. return _ComputationType.BACKWARD_WEIGHT
  74. elif action == "UNSHARD":
  75. return _ComputationType.UNSHARD
  76. elif action == "RESHARD":
  77. return _ComputationType.RESHARD
  78. elif action == "SEND_F":
  79. return _ComputationType.SEND_F
  80. elif action == "RECV_F":
  81. return _ComputationType.RECV_F
  82. elif action == "SEND_B":
  83. return _ComputationType.SEND_B
  84. elif action == "RECV_B":
  85. return _ComputationType.RECV_B
  86. elif action == "B":
  87. return _ComputationType.FULL_BACKWARD
  88. elif action == "OVERLAP_F_B":
  89. return _ComputationType.OVERLAP_F_B
  90. elif action == "REDUCE_GRAD":
  91. return _ComputationType.REDUCE_GRAD
  92. else:
  93. raise RuntimeError(f"Invalid computation type {action}")
  94. FORWARD = _ComputationType.FORWARD
  95. BACKWARD_INPUT = _ComputationType.BACKWARD_INPUT
  96. BACKWARD_WEIGHT = _ComputationType.BACKWARD_WEIGHT
  97. UNSHARD = _ComputationType.UNSHARD
  98. RESHARD = _ComputationType.RESHARD
  99. SEND_F = _ComputationType.SEND_F
  100. RECV_F = _ComputationType.RECV_F
  101. SEND_B = _ComputationType.SEND_B
  102. RECV_B = _ComputationType.RECV_B
  103. FULL_BACKWARD = _ComputationType.FULL_BACKWARD
  104. OVERLAP_F_B = _ComputationType.OVERLAP_F_B
  105. REDUCE_GRAD = _ComputationType.REDUCE_GRAD
  106. # Convenience shorthand for compute actions only since they are used in 'simple schedule format'
  107. F = FORWARD
  108. I = BACKWARD_INPUT
  109. W = BACKWARD_WEIGHT
  110. B = FULL_BACKWARD
  111. # Helper to parse an action string like 1F0 into a tuple of (stage_index, computation_type, microbatch_index)
  112. _action_regex = re.compile(
  113. r"(\d+)(F|I|B|W|UNSHARD|RESHARD|REDUCE_GRAD|SEND_F|RECV_F|SEND_B|RECV_B)(\d*)"
  114. )
  115. class _Action(NamedTuple):
  116. stage_index: int
  117. computation_type: _ComputationType
  118. microbatch_index: int | None = None
  119. sub_actions: tuple["_Action", ...] | None = None
  120. def __str__(self):
  121. return self.__repr__()
  122. def __repr__(self):
  123. if self.sub_actions is not None:
  124. # Use recursive repr for sub_actions
  125. sub_action_reprs = [repr(sub_action) for sub_action in self.sub_actions]
  126. return f"({';'.join(sub_action_reprs)}){self.computation_type}"
  127. else:
  128. repr_str = str(self.stage_index)
  129. repr_str += str(self.computation_type)
  130. if self.microbatch_index is not None:
  131. repr_str += str(self.microbatch_index)
  132. return repr_str
  133. @property
  134. def is_compute_op(self) -> bool:
  135. return self.computation_type in (
  136. FORWARD,
  137. FULL_BACKWARD,
  138. BACKWARD_INPUT,
  139. BACKWARD_WEIGHT,
  140. OVERLAP_F_B,
  141. )
  142. @staticmethod
  143. def from_str(action_string: str):
  144. """
  145. Reverse of __repr__
  146. String should be formatted as [stage][action type][(microbatch)]
  147. e.g. `2F0`, `1UNSHARD`, `3SEND_F1`
  148. """
  149. action_string = action_string.strip()
  150. if action_string == "":
  151. return None
  152. # Check for sub_actions format: [sub_action1;sub_action2;...]ComputationType
  153. if action_string.startswith("(") and ")" in action_string:
  154. # Find the closing bracket to separate sub_actions from computation type
  155. bracket_end = action_string.find(")")
  156. sub_part = action_string[
  157. 1:bracket_end
  158. ] # Remove '[' and get content before ']'
  159. computation_type_part = action_string[
  160. bracket_end + 1 :
  161. ] # Get part after ']'
  162. # Parse sub_actions
  163. sub_actions = []
  164. if sub_part.strip():
  165. for sub_str in sub_part.split(";"):
  166. sub_action = _Action.from_str(sub_str.strip())
  167. if sub_action is not None:
  168. sub_actions.append(sub_action)
  169. # For sub_actions format, we create an action with just the computation type
  170. # The stage_index and microbatch_index are not meaningful for the container action
  171. return _Action(
  172. stage_index=-1, # Placeholder, not meaningful for sub_actions container
  173. computation_type=_ComputationType.from_str(computation_type_part),
  174. microbatch_index=None,
  175. sub_actions=tuple(sub_actions) if sub_actions else None,
  176. )
  177. # Handle regular single action format
  178. if match := _action_regex.match(action_string):
  179. stage_index, computation_type, microbatch_index = match.groups()
  180. return _Action(
  181. int(stage_index),
  182. _ComputationType.from_str(computation_type),
  183. int(microbatch_index) if len(microbatch_index) else None,
  184. )
  185. elif action_string == "":
  186. return None
  187. raise RuntimeError(
  188. f"Invalid action string: {action_string}, should be formatted as [stage][action type][(microbatch)] e.g. 2F0"
  189. )
  190. @lru_cache
  191. def _get_profiler_function_name(action: _Action) -> str:
  192. return f"PP:{str(action)}"
  193. def _format_pipeline_order(
  194. pipeline_order: dict[int, list[_Action | None]],
  195. error_step_number: int | None = None,
  196. ) -> str:
  197. """
  198. Formats the pipeline order in a timestep (row) x rank (column) grid of actions
  199. and returns the formatted string.
  200. If `error_step_number` is passed in, an additional label will be added to signify which step
  201. that it is erroring on.
  202. """
  203. # don't mutate the original
  204. pipeline_order = copy.deepcopy(pipeline_order)
  205. # Replace None with ""
  206. for rank in pipeline_order:
  207. for i in range(len(pipeline_order[rank])):
  208. if pipeline_order[rank][i] is None:
  209. # TODO make a real 'None action' that prints as empty string and make mypy happy
  210. pipeline_order[rank][i] = "" # type: ignore[call-overload]
  211. # Calculate the maximum number of steps across all ranks
  212. num_steps = max(len(actions) for actions in pipeline_order.values())
  213. step_labels = [
  214. "Step " + str(i).zfill(len(str(num_steps - 1))) for i in range(num_steps)
  215. ]
  216. # Sorting the dictionary by keys and retrieving values in that order
  217. rank_actions = [
  218. pipeline_order.get(key, [""] * num_steps) for key in sorted(pipeline_order)
  219. ]
  220. # Transpose the list of lists (rows to columns)
  221. # pyrefly: ignore [no-matching-overload]
  222. transposed_actions = list(itertools.zip_longest(*rank_actions, fillvalue=""))
  223. # Generate column labels for ranks
  224. num_ranks = len(pipeline_order)
  225. rank_labels = ["Rank " + str(i) for i in range(num_ranks)]
  226. # Calculate the maximum length of each column, considering labels
  227. max_lengths = [
  228. max(len(str(item)) if item is not None else 0 for item in col)
  229. for col in zip(step_labels, *transposed_actions)
  230. ]
  231. # Format the header row with rank labels
  232. header_row = " " * (len(step_labels[0]) + 2) + " ".join(
  233. f"{label:<{max_lengths[i]}}" for i, label in enumerate(rank_labels)
  234. )
  235. # Format each row with its corresponding label
  236. formatted_rows = [
  237. f"{label}: "
  238. + " ".join(f"{str(item):<{max_lengths[i]}}" for i, item in enumerate(row))
  239. + (
  240. " <-- ERROR HERE"
  241. if error_step_number is not None
  242. and int(label.split()[1]) == error_step_number
  243. else ""
  244. )
  245. for label, row in zip(step_labels, transposed_actions)
  246. ]
  247. # Join the rows into a single string
  248. formatted_table = header_row + "\n" + "\n".join(formatted_rows) + "\n"
  249. return formatted_table
  250. class _PipelineSchedule(ABC):
  251. def __init__(
  252. self,
  253. n_microbatches: int,
  254. loss_fn: Callable[..., torch.Tensor] | None = None,
  255. args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
  256. kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
  257. output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
  258. scale_grads: bool = True,
  259. ):
  260. # From arguments
  261. self._n_microbatches = n_microbatches
  262. self._loss_fn = loss_fn
  263. # See documentation in `PipelineScheduleSingle` / `PipelineScheduleMulti`
  264. self.scale_grads = scale_grads
  265. # Chunking specification for positional inputs. (default: `None`)
  266. self._args_chunk_spec = args_chunk_spec
  267. # Chunking specification for keyword inputs. (default: `None`)
  268. self._kwargs_chunk_spec = kwargs_chunk_spec
  269. self._output_merge_spec = output_merge_spec
  270. """
  271. # args_chunk_spec and kwargs_chunk_spec specify how to chunk inputs.
  272. # They are used to convert batch to microbatches in `step(x)`. See
  273. # `TensorChunkSpec` for helper methods for creating them.
  274. """
  275. # Derived
  276. self._has_backward = self._loss_fn is not None
  277. # Holds the losses for each microbatch.
  278. self._internal_losses: list[torch.Tensor] = []
  279. logger.info("Using %s", self.__class__.__name__)
  280. def _maybe_compute_loss(self, stage, output, target_mbs, mb_index):
  281. if stage.is_last and self._loss_fn is not None:
  282. loss = self._compute_loss(output, target_mbs[mb_index]) # type: ignore[index]
  283. self._internal_losses.append(loss)
  284. def _maybe_get_loss(self, stage, mb_index):
  285. valid_index = 0 <= mb_index < len(self._internal_losses)
  286. if stage.is_last and self._loss_fn is not None and valid_index:
  287. return self._internal_losses[mb_index]
  288. elif len(self._internal_losses) != 0 and not valid_index:
  289. raise RuntimeError(
  290. f"Loss for microbatch {mb_index} is not available. "
  291. f"Available losses for microbatches: {self._internal_losses}"
  292. )
  293. else:
  294. return None
  295. def _update_losses(self, stages, losses):
  296. """
  297. Update the losses to those in the internal state
  298. """
  299. # if stages not a list turn into a list
  300. if not isinstance(stages, list):
  301. stages = [stages]
  302. contains_last_stage = any(stage.is_last for stage in stages)
  303. # Return losses if there is a container passed in
  304. if contains_last_stage and losses is not None:
  305. if len(self._internal_losses) != self._n_microbatches:
  306. raise RuntimeError(
  307. f"Expecting {self._n_microbatches} losses but got {len(self._internal_losses)}"
  308. )
  309. # Clean external container first
  310. losses.clear()
  311. # Copy internal losses to external container
  312. losses.extend(self._internal_losses)
  313. self._internal_losses.clear()
  314. @abstractmethod
  315. def _step_microbatches(
  316. self,
  317. arg_mbs: list | None = None,
  318. kwarg_mbs: list | None = None,
  319. target_mbs: list | None = None,
  320. losses: list | None = None,
  321. return_outputs: bool = True,
  322. ):
  323. """
  324. Run one iteration of the pipeline schedule with list of microbatches.
  325. Will go through all the microbatches according to the schedule
  326. implementation.
  327. Args:
  328. microbatches: list of microbatch args.
  329. return_outputs: whether to return the outputs from the last stage.
  330. """
  331. raise NotImplementedError
  332. @abstractmethod
  333. def step(
  334. self,
  335. *args,
  336. target=None,
  337. losses: list | None = None,
  338. return_outputs=True,
  339. **kwargs,
  340. ):
  341. """
  342. Run one iteration of the pipeline schedule with *whole-batch* input.
  343. Will chunk the input into microbatches automatically, and go through the
  344. microbatches according to the schedule implementation.
  345. args: positional arguments to the model (as in non-pipeline case).
  346. kwargs: keyword arguments to the model (as in non-pipeline case).
  347. target: target for the loss function.
  348. losses: a list to store the losses for each microbatch.
  349. return_outputs: whether to return the outputs from the last stage.
  350. """
  351. raise NotImplementedError
  352. def eval(self, *args, target=None, losses: list | None = None, **kwargs):
  353. """
  354. Run one iteration of the pipeline schedule with *whole-batch* input.
  355. Will chunk the input into microbatches automatically, and go through the
  356. microbatches, calling forward only.
  357. args: positional arguments to the model (as in non-pipeline case).
  358. kwargs: keyword arguments to the model (as in non-pipeline case).
  359. target: target values for the loss function.
  360. losses: a list to store the losses for each microbatch.
  361. """
  362. # Save the original has_backward state
  363. original_has_backward = self._has_backward
  364. try:
  365. self._has_backward = False
  366. return self.step(*args, target=target, losses=losses, **kwargs)
  367. finally:
  368. # Restore the original state
  369. self._has_backward = original_has_backward
  370. def _check_inputs(
  371. self,
  372. arg_mbs: list | None = None,
  373. kwarg_mbs: list | None = None,
  374. target_mbs: list | None = None,
  375. losses: list | None = None,
  376. ) -> tuple[list, list]:
  377. """
  378. Pre-process/check inputs
  379. """
  380. def check_type_and_len(mbs, name: str):
  381. if not isinstance(mbs, list):
  382. raise TypeError(f"{name} must be a list but got a {type(mbs)}")
  383. if len(mbs) != self._n_microbatches:
  384. raise ValueError(
  385. f"Expecting {self._n_microbatches} {name} but got {len(mbs)}"
  386. )
  387. if arg_mbs is not None:
  388. check_type_and_len(arg_mbs, "arg_mbs")
  389. else:
  390. arg_mbs = [()] * self._n_microbatches
  391. if kwarg_mbs is not None:
  392. check_type_and_len(kwarg_mbs, "kwarg_mbs")
  393. else:
  394. kwarg_mbs = [{}] * self._n_microbatches
  395. if target_mbs is not None:
  396. check_type_and_len(target_mbs, "target_mbs")
  397. if losses is not None:
  398. if not isinstance(losses, list):
  399. raise TypeError(f"losses must be a list but got a {type(losses)}")
  400. return arg_mbs, kwarg_mbs
  401. def _compute_loss(self, output, target):
  402. return self._loss_fn(output, target) # type: ignore[misc]
  403. def _split_inputs(
  404. self,
  405. args: tuple[Any, ...],
  406. kwargs: dict[str, Any] | None = None,
  407. ):
  408. """
  409. Splits a full-batch input into chunks (i.e. microbatches) and returns
  410. the chunks
  411. """
  412. if args or kwargs:
  413. args_split, kwargs_split = split_args_kwargs_into_chunks(
  414. args,
  415. kwargs,
  416. self._n_microbatches,
  417. self._args_chunk_spec,
  418. self._kwargs_chunk_spec,
  419. )
  420. return args_split, kwargs_split
  421. else:
  422. # Empty inputs (e.g. when called on middle stages)
  423. # Return a list of empty tuples/dicts with matching length as chunks
  424. return [()] * self._n_microbatches, [{}] * self._n_microbatches
  425. def _merge_outputs(self, output_chunks: list[Any]) -> Any:
  426. """
  427. Merge output chunks back to a batch state.
  428. If output_merge_spec is None, the utility will merge output chunks by dimension 0 (batch dim).
  429. """
  430. return merge_chunks(
  431. output_chunks,
  432. self._output_merge_spec,
  433. )
  434. def _batch_p2p(p2p_ops: list[dist.P2POp], desc: str | None = None) -> list[dist.Work]:
  435. """
  436. Simple wrapper over batch_isend_irecv from torch.distributed, which just adds a descriptive logger on top.
  437. """
  438. if len(p2p_ops) == 0:
  439. return []
  440. desc_str = f"{desc}, " if desc else ""
  441. logger.debug("batch_p2p %s%s", desc_str, p2p_ops)
  442. return dist.batch_isend_irecv(p2p_ops)
  443. def _sorted_batch_p2p(
  444. p2p_ops: list[dist.P2POp], desc: str | None = None
  445. ) -> dict[int, list[dist.Work]]:
  446. """
  447. Sorts the list of P2P ops by the peer rank, and then calls
  448. batch_isend_irecv. Return a dictionary of works by peer rank. This function
  449. helps us avoid hangs in case of skip connections.
  450. """
  451. # Arrange p2p_ops by peer rank:
  452. # int is the peer rank;
  453. # List is the list of ops towards the peer
  454. ops_by_peer: dict[int, list[dist.P2POp]] = defaultdict(list)
  455. work_by_peer: dict[int, list[dist.Work]] = {}
  456. if len(p2p_ops) == 0:
  457. return work_by_peer
  458. # Classify the ops by peer rank
  459. for op in p2p_ops:
  460. ops_by_peer[op.peer].append(op)
  461. # Call batch_isend_irecv per peer, in sorted order of the peers (to avoid hangs)
  462. for peer, ops in sorted(ops_by_peer.items()):
  463. work_by_peer[peer] = _batch_p2p(ops, desc=desc)
  464. return work_by_peer
  465. def _wait_batch_p2p(work: list[dist.Work]):
  466. """
  467. Waits for a list of dist.Work (typically from _batch_p2p / _sorted_batch_p2p).
  468. """
  469. for w in work:
  470. w.wait()
  471. class PipelineScheduleSingle(_PipelineSchedule):
  472. """
  473. Base class for single-stage schedules.
  474. Implements the `step` method.
  475. Derived classes should implement `_step_microbatches`.
  476. Gradients are scaled by num_microbatches depending on the `scale_grads` argument, defaulting to True. This setting
  477. should match the configuration of your loss_fn, which may either average losses (scale_grads=True)
  478. or sum losses (scale_grads=False).
  479. """
  480. def __init__(
  481. self,
  482. stage: _PipelineStageBase,
  483. n_microbatches: int,
  484. loss_fn: Callable | None = None,
  485. args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
  486. kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
  487. output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
  488. scale_grads: bool = True,
  489. ):
  490. # Init parent
  491. super().__init__(
  492. n_microbatches=n_microbatches,
  493. loss_fn=loss_fn,
  494. args_chunk_spec=args_chunk_spec,
  495. kwargs_chunk_spec=kwargs_chunk_spec,
  496. output_merge_spec=output_merge_spec,
  497. scale_grads=scale_grads,
  498. )
  499. # Self attributes
  500. self._stage = stage
  501. self._num_stages = stage.num_stages
  502. self._stage_forward_initialized = False
  503. self._stage_backward_initialized = False
  504. if n_microbatches < self._num_stages:
  505. raise ValueError(
  506. f"Number of microbatches ({n_microbatches}) must be greater than \
  507. or equal to the number of stages ({self._num_stages})."
  508. )
  509. self.pipeline_order: dict[int, list[_Action | None]] | None = (
  510. self._get_pipeline_order()
  511. )
  512. def _initialize_stage(self, args, kwargs):
  513. if not self._stage_forward_initialized:
  514. # Prepare the communication needed for the pipeline schedule execution
  515. # This is needed because during execution we always perform a series of batch P2P ops
  516. # The first call of the batched P2P needs to involve the global group
  517. all_ops: list[dist.P2POp] = []
  518. all_ops.extend(self._stage._get_init_p2p_neighbors_ops())
  519. _wait_batch_p2p(_batch_p2p(all_ops))
  520. self._stage._prepare_forward_infra(self._n_microbatches, args, kwargs)
  521. self._stage_forward_initialized = True
  522. if self._has_backward and not self._stage_backward_initialized:
  523. self._stage._prepare_backward_infra(self._n_microbatches)
  524. self._stage_backward_initialized = True
  525. def step(
  526. self,
  527. *args,
  528. target=None,
  529. losses: list | None = None,
  530. return_outputs: bool = True,
  531. **kwargs,
  532. ):
  533. """
  534. Run one iteration of the pipeline schedule with *whole-batch* input.
  535. Will chunk the input into microbatches automatically, and go through the
  536. microbatches according to the schedule implementation.
  537. args: positional arguments to the model (as in non-pipeline case).
  538. kwargs: keyword arguments to the model (as in non-pipeline case).
  539. target: target for the loss function.
  540. losses: a list to store the losses for each microbatch.
  541. return_outputs: whether to return the outputs from the last stage.
  542. """
  543. if self._has_backward and not torch.is_grad_enabled():
  544. raise RuntimeError(
  545. "step() requires gradients to be enabled for backward computation; "
  546. "it should not be used under torch.no_grad() context. "
  547. "Please call eval() instead."
  548. )
  549. # Set the same has_backward flag for stage object
  550. self._stage.has_backward = self._has_backward
  551. # Clean per iteration
  552. self._stage.clear_runtime_states()
  553. # Split inputs into microbatches
  554. args_split, kwargs_split = self._split_inputs(args, kwargs)
  555. # Split target into microbatches
  556. if target is not None:
  557. targets_split = list(torch.tensor_split(target, self._n_microbatches))
  558. else:
  559. targets_split = None
  560. # Run microbatches
  561. self._step_microbatches(
  562. args_split, kwargs_split, targets_split, losses, return_outputs
  563. )
  564. # Return merged results per original format
  565. if self._stage.is_last and return_outputs:
  566. return self._merge_outputs(self._stage.output_chunks)
  567. else:
  568. return None
  569. def _get_pipeline_order(self) -> dict[int, list[_Action | None]] | None:
  570. """
  571. Returns the pipeline execution order as a schedule IR.
  572. The returned IR is a dictionary mapping rank IDs to lists of actions.
  573. Each action is either an _Action object representing computation to perform,
  574. or None representing a deliberate idle step.
  575. The None values are used to represent pipeline bubbles where a rank
  576. must wait for dependencies from other ranks before proceeding. However
  577. during execution, with the _PipelineScheduleRuntime, these Nones are
  578. skipped since the relevant communication (send/recv) will be scheduled and waited on.
  579. Returns:
  580. A dictionary mapping rank -> list of actions
  581. """
  582. return None
  583. class _ScheduleForwardOnly(PipelineScheduleSingle):
  584. """
  585. The forward-only schedule.
  586. Will go through all the microbatches and perform only the forward pass
  587. """
  588. def _step_microbatches(
  589. self,
  590. arg_mbs: list | None = None,
  591. kwarg_mbs: list | None = None,
  592. target_mbs: list | None = None,
  593. losses: list | None = None,
  594. return_outputs: bool = True,
  595. ):
  596. """
  597. Run one iteration of the pipeline schedule
  598. """
  599. if target_mbs is not None or losses is not None:
  600. raise RuntimeError(
  601. "Forward-only schedule does not support loss computation"
  602. )
  603. arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
  604. self._initialize_stage(arg_mbs[0], kwarg_mbs[0])
  605. # Delay send waits
  606. fwd_sends_to_wait: list[list[dist.Work]] = []
  607. # Run microbatches
  608. for i in range(self._n_microbatches):
  609. with record_function(f"Forward {i}"):
  610. ops = self._stage.get_fwd_recv_ops(i)
  611. works = _sorted_batch_p2p(ops, desc="fwd_recv")
  612. for work in works.values():
  613. _wait_batch_p2p(work)
  614. self._stage.forward_one_chunk(i, arg_mbs[i], kwarg_mbs[i]) # type: ignore[index]
  615. ops = self._stage.get_fwd_send_ops(i)
  616. works = _sorted_batch_p2p(ops, desc="fwd_send")
  617. fwd_sends_to_wait.extend(works.values())
  618. logger.debug("[%s] Forwarded microbatch %s", self._stage.stage_index, i)
  619. # Wait for all forward sends to finish
  620. # This should not have performance impact because by the time the first
  621. # backward arrives all the forward sends should have been finished.
  622. for work in fwd_sends_to_wait:
  623. _wait_batch_p2p(work)
  624. class ScheduleGPipe(PipelineScheduleSingle):
  625. """
  626. The GPipe schedule.
  627. Will go through all the microbatches in a fill-drain manner.
  628. """
  629. def _step_microbatches(
  630. self,
  631. arg_mbs: list | None = None,
  632. kwarg_mbs: list | None = None,
  633. target_mbs: list | None = None,
  634. losses: list | None = None,
  635. return_outputs: bool = True,
  636. ):
  637. """
  638. Run one iteration of the pipeline schedule with list of microbatches.
  639. Will go through all the microbatches according to the GPipe schedule.
  640. Args:
  641. microbatches: list of microbatch args.
  642. return_outputs: whether to return the outputs from the last stage.
  643. """
  644. arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
  645. self._initialize_stage(arg_mbs[0], kwarg_mbs[0])
  646. # Delay send waits
  647. fwd_sends_to_wait: list[list[dist.Work]] = []
  648. # Run microbatches
  649. for i in range(self._n_microbatches):
  650. with record_function(f"Forward {i}"):
  651. ops = self._stage.get_fwd_recv_ops(i)
  652. works = _sorted_batch_p2p(ops, desc="fwd_recv")
  653. for work in works.values():
  654. _wait_batch_p2p(work)
  655. output = self._stage.forward_one_chunk(
  656. i, arg_mbs[i], kwarg_mbs[i], save_forward_output=return_outputs
  657. ) # type: ignore[index]
  658. ops = self._stage.get_fwd_send_ops(i)
  659. works = _sorted_batch_p2p(ops, desc="fwd_send")
  660. fwd_sends_to_wait.extend(works.values())
  661. logger.debug("[%s] Forwarded microbatch %s", self._stage.stage_index, i)
  662. self._maybe_compute_loss(self._stage, output, target_mbs, i)
  663. # Wait for all forward sends to finish
  664. # This should not have performance impact because by the time the first
  665. # backward arrives all the forward sends should have been finished.
  666. for work in fwd_sends_to_wait:
  667. _wait_batch_p2p(work)
  668. # Run backward
  669. # Delay send waits
  670. bwd_sends_to_wait: list[list[dist.Work]] = []
  671. for i in range(self._n_microbatches):
  672. with record_function(f"Backward {i}"):
  673. ops = self._stage.get_bwd_recv_ops(i)
  674. works = _sorted_batch_p2p(ops, desc="bwd_recv")
  675. for work in works.values():
  676. _wait_batch_p2p(work)
  677. loss = self._maybe_get_loss(self._stage, i)
  678. self._stage.backward_one_chunk(
  679. i,
  680. loss=loss,
  681. last_backward=i == self._n_microbatches - 1,
  682. )
  683. ops = self._stage.get_bwd_send_ops(i)
  684. works = _sorted_batch_p2p(ops, desc="bwd_send")
  685. bwd_sends_to_wait.extend(works.values())
  686. logger.debug("[%s] Backwarded microbatch %s", self._stage.stage_index, i)
  687. # Wait for all backward sends to finish
  688. for work in bwd_sends_to_wait:
  689. _wait_batch_p2p(work)
  690. # Update losses if there is a container passed in
  691. self._update_losses(self._stage, losses)
  692. self._stage.perform_reduce_grad(self._n_microbatches if self.scale_grads else 1)
  693. def _get_pipeline_order(self) -> dict[int, list[_Action | None]] | None:
  694. """
  695. Returns the pipeline order for GPipe schedule.
  696. See base method in PipelineScheduleSingle for details on the schedule IR format.
  697. """
  698. pipeline_order = {}
  699. pp_group_size = self._num_stages
  700. for rank in range(pp_group_size):
  701. actions: list[_Action | None] = []
  702. # 1. Initial delay based on rank position
  703. warmup_delay = rank
  704. actions.extend([None] * warmup_delay)
  705. # 2. Forward passes for all microbatches
  706. for mb_idx in range(self._n_microbatches):
  707. actions.append(_Action(rank, _ComputationType.FORWARD, mb_idx))
  708. # 3. Wait period before backward passes can begin
  709. backward_delay = 3 * (pp_group_size - 1 - rank)
  710. actions.extend([None] * backward_delay)
  711. # 4. Backward passes for all microbatches
  712. for mb_idx in range(self._n_microbatches):
  713. actions.append(_Action(rank, _ComputationType.FULL_BACKWARD, mb_idx))
  714. pipeline_order[rank] = _add_reduce_grad(actions, self._n_microbatches)
  715. return pipeline_order # type: ignore[return-value]
  716. class Schedule1F1B(PipelineScheduleSingle):
  717. """
  718. The 1F1B schedule.
  719. Will perform one forward and one backward on the microbatches in steady state.
  720. """
  721. def _step_microbatches(
  722. self,
  723. arg_mbs: list | None = None,
  724. kwarg_mbs: list | None = None,
  725. target_mbs: list | None = None,
  726. losses: list | None = None,
  727. return_outputs: bool = True,
  728. ):
  729. """
  730. Run one iteration of the pipeline schedule with list of microbatches.
  731. Will go through all the microbatches according to the 1F1B schedule.
  732. Args:
  733. microbatches: list of microbatch args.
  734. return_outputs: whether to return the outputs from the last stage.
  735. """
  736. arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
  737. self._initialize_stage(arg_mbs[0], kwarg_mbs[0])
  738. # Last stage has 1 warmup, second-to-last 2 warmups, ...
  739. # first stage `num_stages` warmups
  740. warmup_chunks = min(
  741. self._n_microbatches,
  742. self._num_stages - self._stage.stage_index,
  743. )
  744. # Chunk counters
  745. fwd_mb_index = 0
  746. bwd_mb_index = 0
  747. # Warmup phase
  748. send_work: list[dist.Work] = []
  749. fwd_sends = []
  750. for _ in range(warmup_chunks):
  751. # Receive activations
  752. fwd_recvs = self._stage.get_fwd_recv_ops(fwd_mb_index)
  753. _wait_batch_p2p(_batch_p2p(fwd_recvs, desc="fwd_recv"))
  754. # Compute
  755. output = self._stage.forward_one_chunk(
  756. fwd_mb_index,
  757. arg_mbs[fwd_mb_index],
  758. kwarg_mbs[fwd_mb_index],
  759. save_forward_output=return_outputs,
  760. ) # type: ignore[index]
  761. # Clear previous chunk's forward sends (hopefully they have well
  762. # finished, otherwise, we are heavily communication bound, in which
  763. # case it doesn't create a lot of benefit to compute next chunk
  764. # eagerly either)
  765. _wait_batch_p2p(send_work)
  766. # Send activations
  767. fwd_sends = self._stage.get_fwd_send_ops(fwd_mb_index)
  768. if fwd_mb_index != warmup_chunks - 1:
  769. # Safe to fire
  770. send_work = _batch_p2p(fwd_sends, desc="fwd_send")
  771. # otherwise:
  772. # The last forward send is left for fuse with first 1B in 1B1F below
  773. # Compute loss
  774. self._maybe_compute_loss(self._stage, output, target_mbs, fwd_mb_index)
  775. fwd_mb_index += 1
  776. # Now we should have send ops left over, to be fused with first 1B of 1B1F phase below.
  777. # 1B1F phase
  778. while True: # Don't worry, we have a break inside
  779. # We actually do 1B first as the `1B1F` name indicates, so prepare its recv ops
  780. bwd_recvs = self._stage.get_bwd_recv_ops(bwd_mb_index)
  781. # Now, we need to fire the fwd_sends and bwd_recvs together
  782. _wait_batch_p2p(_batch_p2p(fwd_sends + bwd_recvs, desc="fwd_send_bwd_recv"))
  783. # Backward one chunk
  784. loss = self._maybe_get_loss(self._stage, bwd_mb_index)
  785. self._stage.backward_one_chunk(
  786. bwd_mb_index,
  787. loss=loss,
  788. last_backward=bwd_mb_index == self._n_microbatches - 1,
  789. )
  790. # Get the bwd send ops, but don't fire, to be fused with the 1F below
  791. bwd_sends = self._stage.get_bwd_send_ops(bwd_mb_index)
  792. bwd_mb_index += 1
  793. if fwd_mb_index == self._n_microbatches:
  794. # We are done with 1B1F, so break with some left-over bwd_sends
  795. break
  796. # We prepare 1F of the `1B1F`
  797. fwd_recvs = self._stage.get_fwd_recv_ops(fwd_mb_index)
  798. # Fuse it with bwd_sends above
  799. _wait_batch_p2p(_batch_p2p(bwd_sends + fwd_recvs, desc="bwd_send_fwd_recv"))
  800. # Now do the fwd
  801. output = self._stage.forward_one_chunk(
  802. fwd_mb_index,
  803. arg_mbs[fwd_mb_index],
  804. kwarg_mbs[fwd_mb_index],
  805. save_forward_output=return_outputs,
  806. ) # type: ignore[index]
  807. # Compute loss
  808. self._maybe_compute_loss(self._stage, output, target_mbs, fwd_mb_index)
  809. # Get the fwd send ops, but don't fire, leave it for the next iter (wrap-around)
  810. fwd_sends = self._stage.get_fwd_send_ops(fwd_mb_index)
  811. fwd_mb_index += 1
  812. # Remember we still have some bwd_sends left over after the break? Now it is time to fire it
  813. send_work = _batch_p2p(bwd_sends, desc="bwd_send")
  814. # Cooldown
  815. while bwd_mb_index < self._n_microbatches:
  816. # prepare bwd recv ops
  817. bwd_recvs = self._stage.get_bwd_recv_ops(bwd_mb_index)
  818. _wait_batch_p2p(_batch_p2p(bwd_recvs, desc="bwd_recv"))
  819. # Backward one chunk
  820. loss = self._maybe_get_loss(self._stage, bwd_mb_index)
  821. self._stage.backward_one_chunk(
  822. bwd_mb_index,
  823. loss=loss,
  824. last_backward=bwd_mb_index == self._n_microbatches - 1,
  825. )
  826. # Clear previous chunk's backward sends (hopefully they have well finished)
  827. _wait_batch_p2p(send_work)
  828. # Get the bwd send ops, fire it
  829. bwd_sends = self._stage.get_bwd_send_ops(bwd_mb_index)
  830. send_work = _batch_p2p(bwd_sends, desc="bwd_send")
  831. bwd_mb_index += 1
  832. # Wait for the last backward send to finish
  833. _wait_batch_p2p(send_work)
  834. # Return losses if there is a container passed in
  835. self._update_losses(self._stage, losses)
  836. self._stage.perform_reduce_grad(self._n_microbatches if self.scale_grads else 1)
  837. def _get_pipeline_order(self) -> dict[int, list[_Action | None]] | None:
  838. """
  839. Returns the pipeline order for 1F1B schedule.
  840. See base method in PipelineScheduleSingle for details on the schedule IR format.
  841. """
  842. pipeline_order = {}
  843. pp_group_size = self._num_stages
  844. for rank in range(pp_group_size):
  845. actions: list[_Action | None] = []
  846. # 1. Warmup phase: initial delay based on rank
  847. actions.extend([None] * rank)
  848. # 2. Initial forward passes before 1F1B phase
  849. num_forward = (pp_group_size - 1) - rank
  850. forward_mb = 0
  851. for i in range(num_forward):
  852. actions.append(_Action(rank, _ComputationType.FORWARD, i))
  853. forward_mb = i
  854. # 3. Wait for backward to be ready
  855. wait_for_1f1b = max(0, 2 * (pp_group_size - 1 - rank))
  856. actions.extend([None] * wait_for_1f1b)
  857. # 4. 1F1B steady state phase
  858. backward_mb = 0
  859. remaining_forward = self._n_microbatches - num_forward
  860. while remaining_forward > 0:
  861. # One forward
  862. forward_mb += 1
  863. actions.append(_Action(rank, _ComputationType.FORWARD, forward_mb))
  864. remaining_forward -= 1
  865. # One backward
  866. actions.append(
  867. _Action(rank, _ComputationType.FULL_BACKWARD, backward_mb)
  868. )
  869. backward_mb += 1
  870. # 5. Cooldown phase: remaining backward passes
  871. remaining_backward = self._n_microbatches - backward_mb
  872. while remaining_backward > 0:
  873. # Add None and backward actions in alternating pattern
  874. # based on distance from the last stage
  875. if (pp_group_size - rank) > 0:
  876. actions.append(None)
  877. # Decrement the wait counter only if we still have backward passes to do
  878. if remaining_backward > 0:
  879. actions.append(
  880. _Action(rank, _ComputationType.FULL_BACKWARD, backward_mb)
  881. )
  882. backward_mb += 1
  883. remaining_backward -= 1
  884. else:
  885. # If we're at the last stage, just add backward actions without None
  886. actions.append(
  887. _Action(rank, _ComputationType.FULL_BACKWARD, backward_mb)
  888. )
  889. backward_mb += 1
  890. remaining_backward -= 1
  891. pipeline_order[rank] = _add_reduce_grad(actions, self._n_microbatches)
  892. return pipeline_order
  893. def _requires_reduce_grad(action_type: _ComputationType) -> bool:
  894. return action_type in (W, B)
  895. def _add_reduce_grad(
  896. actions: list[_Action | None], n_microbatches: int
  897. ) -> list[_Action | None]:
  898. """
  899. REDUCE_GRAD refers to joint across minibatches grad reduction.
  900. reduce_grad frees memory and we want to schedule it just after the last "backward"-like stage.
  901. """
  902. actions_with_reduce_grad: list[_Action | None] = []
  903. cnt: dict[int, int] = defaultdict(int)
  904. def _leaf_action(a, to_schedule):
  905. if _requires_reduce_grad(a.computation_type):
  906. stage_index = a.stage_index
  907. cnt[stage_index] += 1
  908. if cnt[stage_index] == n_microbatches:
  909. to_schedule.append(stage_index)
  910. for a in actions:
  911. if a is None:
  912. continue
  913. actions_with_reduce_grad.append(a)
  914. schedule_reduce_grad_stage_idxs: list[int] = []
  915. if a.computation_type == OVERLAP_F_B and a.sub_actions is not None:
  916. for sub_action in a.sub_actions:
  917. _leaf_action(sub_action, schedule_reduce_grad_stage_idxs)
  918. else:
  919. _leaf_action(a, schedule_reduce_grad_stage_idxs)
  920. for stage_idx in schedule_reduce_grad_stage_idxs:
  921. actions_with_reduce_grad.append(_Action(stage_idx, REDUCE_GRAD, None))
  922. return actions_with_reduce_grad
  923. def _add_unshard_reshard(
  924. compute_actions: list[_Action | None],
  925. max_active_stages: int = 3,
  926. ) -> list[_Action]:
  927. """Given a basic schedule involving only compute actions (F,B,W,OVERLAP_F_B), add UNSHARD/RESHARD actions for FSDP.
  928. UNSHARD refers to fetching the full contents of an FSDP-sharded layer, requiring an all-gather operation.
  929. RESHARD does the opposite, releasing memory (but doing no communication)
  930. We abandon the "timestep lock" during lowering
  931. max_active_stages controls how many prefetches we allow. It should be measured in mb and tuneable but in practice
  932. 3 stages is probably the thing we want?
  933. (to account for having one f and one b active, and something else prefetching?)
  934. """
  935. def next_stage_indices(count: int, next_actions: list[_Action | None]) -> list[int]:
  936. """Remove duplicates (same stage, different microbatch), find next 'count' stages that will do compute."""
  937. seen: set[int] = set()
  938. ret: list[int] = []
  939. for a in next_actions:
  940. if a is not None:
  941. # Handle OVERLAP_F_B actions by checking their sub_actions
  942. if a.computation_type == OVERLAP_F_B and a.sub_actions is not None:
  943. for sub_action in a.sub_actions:
  944. if sub_action.stage_index not in seen:
  945. seen.add(sub_action.stage_index)
  946. ret.append(sub_action.stage_index)
  947. if len(ret) >= count:
  948. break
  949. else:
  950. # Regular action
  951. if a.stage_index not in seen:
  952. seen.add(a.stage_index)
  953. ret.append(a.stage_index)
  954. if len(ret) == count:
  955. break
  956. return ret
  957. active_stages: set[int] = set()
  958. fsdp_aware_actions: list[_Action] = []
  959. def _unshard(stage_index: int):
  960. active_stages.add(stage_index)
  961. fsdp_aware_actions.append(_Action(stage_index, UNSHARD, None))
  962. def _reshard(stage_index: int):
  963. active_stages.remove(stage_index)
  964. fsdp_aware_actions.append(_Action(stage_index, RESHARD, None))
  965. for i, action in enumerate(compute_actions):
  966. if action is None:
  967. continue
  968. # We prefetch the next N stages we'll see, dropping existing stages to make room
  969. next_n = next_stage_indices(max_active_stages, compute_actions[i:])
  970. # Fetch needs to be ordered correctly, so don't use a set
  971. fetch = list(filter(lambda s: s not in active_stages, next_n))
  972. # Unclear what the best policy is for eviction, but we can maintain order so we do
  973. evict = list(filter(lambda s: s not in next_n, active_stages))
  974. # logger.debug(
  975. # "_add_unshard_reshard Step %d active: %s fetch %s, evict %s",
  976. # i,
  977. # active_stages,
  978. # fetch,
  979. # evict,
  980. # )
  981. for stage in evict:
  982. _reshard(stage)
  983. for stage in fetch:
  984. _unshard(stage)
  985. fsdp_aware_actions.append(action)
  986. # Reshard all remaining active stages after processing all operations
  987. for stage in list(active_stages):
  988. _reshard(stage)
  989. return fsdp_aware_actions
  990. def _merge_bw(
  991. compute_actions: list[_Action | None],
  992. ) -> list[_Action]:
  993. """Given a basic schedule involving only compute actions (F,I,W), merge adjacent I and W ops into B ops.
  994. (note: I = BACKWARD_INPUT, W = BACKWARD_WEIGHT, B = FULL_BACKWARD)
  995. B refers to running the whole backward (not separating grad_input and grad_weight), which can be more efficient
  996. in some cases.
  997. """
  998. merged_actions = []
  999. while compute_actions:
  1000. action = compute_actions.pop(0)
  1001. if action is None:
  1002. continue
  1003. # Remove any None actions and find the next non-None action
  1004. while len(compute_actions) and compute_actions[0] is None:
  1005. compute_actions.pop(0)
  1006. # Get the next action if it exists
  1007. next_action = compute_actions[0] if len(compute_actions) > 0 else None
  1008. if (
  1009. action.computation_type == BACKWARD_INPUT
  1010. and next_action is not None
  1011. and next_action.computation_type == BACKWARD_WEIGHT
  1012. and action.stage_index == next_action.stage_index
  1013. and action.microbatch_index == next_action.microbatch_index
  1014. ):
  1015. merged_actions.append(
  1016. _Action(action.stage_index, FULL_BACKWARD, action.microbatch_index)
  1017. )
  1018. compute_actions.pop(0)
  1019. else:
  1020. merged_actions.append(action)
  1021. return merged_actions
  1022. def _add_send_recv(
  1023. compute_actions: dict[int, list[_Action]],
  1024. stage_to_rank: Callable[[int], int],
  1025. num_stages: int,
  1026. ) -> dict[int, list[_Action]]:
  1027. """
  1028. Transforms a compute-only schedule into a complete schedule with communication actions.
  1029. For actions with sub-actions (OVERLAP_F_B) we ensure that all the subactions have been
  1030. computed and the communication is ready
  1031. """
  1032. comm_actions: dict[int, list[_Action]] = {rank: [] for rank in compute_actions}
  1033. prev_actions: dict[int, set[_Action]] = {rank: set() for rank in compute_actions}
  1034. def _has_comms(action: _Action) -> bool:
  1035. if action.computation_type == F:
  1036. return action.stage_index != num_stages - 1 and stage_to_rank(
  1037. action.stage_index + 1
  1038. ) != stage_to_rank(action.stage_index)
  1039. elif action.computation_type in (BACKWARD_INPUT, FULL_BACKWARD):
  1040. return action.stage_index != 0 and stage_to_rank(
  1041. action.stage_index - 1
  1042. ) != stage_to_rank(action.stage_index)
  1043. return False
  1044. def _get_comms(action: _Action) -> tuple[_Action, _Action]:
  1045. assert _has_comms(action), f"{action} is not a valid comm action"
  1046. stage_idx = action.stage_index
  1047. ctype = action.computation_type
  1048. mb_idx = action.microbatch_index
  1049. send = _Action(stage_idx, SEND_F if ctype == F else SEND_B, mb_idx)
  1050. recv_stage_idx = stage_idx + 1 if ctype == F else stage_idx - 1
  1051. recv = _Action(recv_stage_idx, RECV_F if ctype == F else RECV_B, mb_idx)
  1052. return send, recv
  1053. def _ready_to_schedule(action: _Action | None, prev_actions: set[_Action]) -> bool:
  1054. """We don't put our own recv ops in the schedule, we let a sender on another rank put our recv ops in place.
  1055. This helps ensure a sane (non-hanging) ordering of sends and recvs.
  1056. But it also means we might not be able to schedule our next compute action yet.
  1057. """
  1058. if action is None:
  1059. return True
  1060. elif action.computation_type == F and action.stage_index != 0:
  1061. if (
  1062. _Action(action.stage_index, RECV_F, action.microbatch_index)
  1063. in prev_actions
  1064. ):
  1065. return True
  1066. elif (
  1067. _Action(action.stage_index - 1, F, action.microbatch_index)
  1068. in prev_actions
  1069. ):
  1070. return True
  1071. return False
  1072. elif (
  1073. action.computation_type in (BACKWARD_INPUT, FULL_BACKWARD)
  1074. and action.stage_index != num_stages - 1
  1075. ):
  1076. if (
  1077. _Action(action.stage_index, RECV_B, action.microbatch_index)
  1078. in prev_actions
  1079. ):
  1080. return True
  1081. elif (
  1082. _Action(action.stage_index + 1, BACKWARD_INPUT, action.microbatch_index)
  1083. in prev_actions
  1084. ):
  1085. return True
  1086. elif (
  1087. _Action(action.stage_index + 1, FULL_BACKWARD, action.microbatch_index)
  1088. in prev_actions
  1089. ):
  1090. return True
  1091. return False
  1092. else:
  1093. return True
  1094. while compute_actions:
  1095. progress = False
  1096. # go in order of ranks even if dict keys aren't ordered
  1097. for rank in sorted(compute_actions):
  1098. assert len(compute_actions[rank]) > 0, (
  1099. f"{rank=}, {len(compute_actions[rank])=}"
  1100. )
  1101. action = compute_actions[rank][0]
  1102. # handle case where parent action (e.g. OVERLAP_F_B) can be comprised of subactions
  1103. if action is not None and action.sub_actions is not None:
  1104. all_actions = action.sub_actions
  1105. else:
  1106. all_actions = (action,)
  1107. if not all(_ready_to_schedule(a, prev_actions[rank]) for a in all_actions):
  1108. continue
  1109. # The action's dependencies are satisfied, so add to schedule
  1110. if action is not None:
  1111. comm_actions[rank].append(action)
  1112. for a in all_actions:
  1113. prev_actions[rank].add(a)
  1114. if _has_comms(a):
  1115. send, recv = _get_comms(a)
  1116. # TODO we can avoid send/recv if the 2 stages are on the same rank.
  1117. # should we avoid that in the runtime or here?
  1118. comm_actions[rank].append(send)
  1119. prev_actions[rank].add(send)
  1120. comm_actions[stage_to_rank(recv.stage_index)].append(recv)
  1121. prev_actions[stage_to_rank(recv.stage_index)].add(recv)
  1122. compute_actions[rank].pop(0)
  1123. if len(compute_actions[rank]) == 0:
  1124. del compute_actions[rank]
  1125. progress = True
  1126. assert progress, "Malformed compute schedule, can't schedule sends/recvs"
  1127. return comm_actions
  1128. def _validate_schedule(
  1129. actions: dict[int, list[_Action | None]],
  1130. pp_group_size: int,
  1131. num_stages: int,
  1132. num_microbatches: int,
  1133. ) -> dict[int, int]:
  1134. assert len(actions) == pp_group_size, (
  1135. f"Schedule has incorrect number of ranks - expected {pp_group_size}, actual {len(actions)}"
  1136. )
  1137. for rank in range(pp_group_size):
  1138. assert rank in actions, f"Schedule is missing actions for rank {rank}"
  1139. # We will count all the actions per stage and ensure they happen in a valid order
  1140. # (e.g. F before (B, I) before W for a given microbatch)
  1141. stage_actions: dict[int, dict[_ComputationType, set]] = {
  1142. stage_id: {
  1143. F: set(),
  1144. B: set(),
  1145. I: set(),
  1146. W: set(),
  1147. }
  1148. for stage_id in range(num_stages)
  1149. }
  1150. stage_index_to_rank_mapping = {}
  1151. def _process_action(action: _Action, rank: int, step: int):
  1152. """Process a single action and update stage_actions and stage_index_to_rank_mapping"""
  1153. s_id = action.stage_index
  1154. ctype = action.computation_type
  1155. mb_id = action.microbatch_index
  1156. if ctype == F:
  1157. stage_actions[s_id][F].add(mb_id)
  1158. elif ctype == B:
  1159. if mb_id not in stage_actions[s_id][F]:
  1160. error_msg = (
  1161. f"Rank {rank}, step {step}: Running Full Backward for stage {s_id}, "
  1162. f"microbatch {mb_id} without first running Forward"
  1163. )
  1164. formatted_schedule = _format_pipeline_order(
  1165. actions, error_step_number=step
  1166. )
  1167. full_error_msg = (
  1168. f"{error_msg}\n\nFull pipeline schedule:\n{formatted_schedule}"
  1169. )
  1170. raise AssertionError(full_error_msg)
  1171. stage_actions[s_id][B].add(mb_id)
  1172. elif ctype == I:
  1173. if mb_id not in stage_actions[s_id][F]:
  1174. error_msg = (
  1175. f"Rank {rank}, step {step}: Running Backward Input for stage {s_id}, "
  1176. f"microbatch {mb_id} without first running Forward"
  1177. )
  1178. formatted_schedule = _format_pipeline_order(
  1179. actions, error_step_number=step
  1180. )
  1181. full_error_msg = (
  1182. f"{error_msg}\n\nFull pipeline schedule:\n{formatted_schedule}"
  1183. )
  1184. raise AssertionError(full_error_msg)
  1185. stage_actions[s_id][I].add(mb_id)
  1186. elif ctype == W:
  1187. if mb_id not in stage_actions[s_id][I]:
  1188. error_msg = (
  1189. f"Rank {rank}, step {step}: Running Backward Weight for stage {s_id}, "
  1190. f"microbatch {mb_id} without first running Backward Input"
  1191. )
  1192. formatted_schedule = _format_pipeline_order(
  1193. actions, error_step_number=step
  1194. )
  1195. full_error_msg = (
  1196. f"{error_msg}\n\nFull pipeline schedule:\n{formatted_schedule}"
  1197. )
  1198. raise AssertionError(full_error_msg)
  1199. stage_actions[s_id][W].add(mb_id)
  1200. if s_id not in stage_index_to_rank_mapping:
  1201. stage_index_to_rank_mapping[s_id] = rank
  1202. else:
  1203. existing_rank = stage_index_to_rank_mapping[s_id]
  1204. assert rank == existing_rank, (
  1205. f"Rank {rank}, step {step}: Stage {s_id} is assigned to both rank {rank} and rank {existing_rank}"
  1206. )
  1207. for rank in actions:
  1208. for step, action in enumerate(actions[rank]):
  1209. if action is None:
  1210. continue
  1211. assert isinstance(action, _Action), (
  1212. f"Rank {rank}, step {step}: Got an invalid action: {action}, expected instance of _Action"
  1213. )
  1214. # Check if action has sub_actions
  1215. if action.sub_actions is not None:
  1216. # Process each sub_action instead of the main action
  1217. for sub_action in action.sub_actions:
  1218. _process_action(sub_action, rank, step)
  1219. else:
  1220. # Process the main action normally
  1221. _process_action(action, rank, step)
  1222. for s_id in stage_actions:
  1223. f_mb = len(stage_actions[s_id][F])
  1224. b_mb = len(stage_actions[s_id][B])
  1225. i_mb = len(stage_actions[s_id][I])
  1226. w_mb = len(stage_actions[s_id][W])
  1227. assert f_mb == num_microbatches, (
  1228. f"Got {f_mb} {F} microbatches for stage {s_id}, expected {num_microbatches}"
  1229. )
  1230. assert i_mb == w_mb, (
  1231. f"Invalid backward microbatches for stage {s_id}: I and W must have equal counts, \
  1232. but got I={i_mb}, W={w_mb}"
  1233. )
  1234. assert b_mb + (i_mb + w_mb) // 2 == num_microbatches, (
  1235. f"Invalid backward microbatches for stage {s_id}: expected {num_microbatches} total backwards, \
  1236. but got B={b_mb}, I={i_mb}, W={w_mb}"
  1237. )
  1238. return stage_index_to_rank_mapping
  1239. class PipelineScheduleMulti(_PipelineSchedule):
  1240. """
  1241. Base class for multi-stage schedules.
  1242. Implements the `step` method.
  1243. Gradients are scaled by num_microbatches depending on the `scale_grads` argument, defaulting to True. This setting
  1244. should match the configuration of your loss_fn, which may either average losses (scale_grads=True)
  1245. or sum losses (scale_grads=False).
  1246. """
  1247. def __init__(
  1248. self,
  1249. stages: list[_PipelineStageBase],
  1250. n_microbatches: int,
  1251. loss_fn: Callable | None = None,
  1252. args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
  1253. kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
  1254. output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
  1255. use_full_backward: bool | None = None,
  1256. scale_grads: bool = True,
  1257. backward_requires_autograd: bool = True,
  1258. ):
  1259. # Init parent
  1260. super().__init__(
  1261. n_microbatches=n_microbatches,
  1262. loss_fn=loss_fn,
  1263. args_chunk_spec=args_chunk_spec,
  1264. kwargs_chunk_spec=kwargs_chunk_spec,
  1265. output_merge_spec=output_merge_spec,
  1266. scale_grads=scale_grads,
  1267. )
  1268. # Self attributes
  1269. self._stages = stages
  1270. self._num_stages = stages[0].num_stages
  1271. self.pp_group_size = stages[0].group_size
  1272. self.rank = stages[0].group_rank
  1273. # Set the pipeline stage states
  1274. self.stage_index_to_group_rank = generate_stage_to_rank_mapping(
  1275. self.pp_group_size, self._num_stages
  1276. )
  1277. for stage in self._stages:
  1278. stage.stage_index_to_group_rank = self.stage_index_to_group_rank
  1279. self._stages_forward_initialized = False
  1280. self._stages_backward_initialized = False
  1281. # avoid putting a reference to 'self' inside the lambda, it creates a ref cycle
  1282. has_loss: bool = self._loss_fn is not None
  1283. self._should_compute_loss = lambda stage: stage.is_last and has_loss
  1284. # This will be set during init of derived schedules
  1285. self.pipeline_order: dict[int, list[_Action | None]] = {}
  1286. # When using a custom backward function, we may or may not need autograd to be used
  1287. # for the backward pass. This flag is used to determine whether or torch.is_grad_enabled()
  1288. # check should be performed before the step function.
  1289. self._backward_requires_autograd = backward_requires_autograd
  1290. if use_full_backward is not None:
  1291. logger.warning(
  1292. "Deprecation warning: 'use_full_backward' is no longer supported. "
  1293. "Simply stop passing it, and everything should still work fine."
  1294. )
  1295. def _initialize_stages(self, args: tuple[Any, ...], kwargs):
  1296. if not self._stages_forward_initialized:
  1297. # Prepare the communication needed for the pipeline schedule execution
  1298. # This is needed because during execution we always perform a series of batch P2P ops
  1299. # The first call of the batched P2P needs to involve the global group
  1300. all_ops: list[dist.P2POp] = []
  1301. for stage in self._stages:
  1302. all_ops.extend(stage._get_init_p2p_neighbors_ops())
  1303. _wait_batch_p2p(_batch_p2p(all_ops))
  1304. # may be 'none' value (if this stage sends its output shapes to the next stage via P2P)
  1305. # or real value (if this stage and next stage are on the same device)
  1306. next_stage_args: tuple[Any, ...] = tuple()
  1307. for stage in self._stages:
  1308. if stage.is_first:
  1309. next_stage_args = stage._prepare_forward_infra(
  1310. self._n_microbatches, args, kwargs
  1311. )
  1312. else:
  1313. next_stage_args = stage._prepare_forward_infra(
  1314. self._n_microbatches, next_stage_args, kwargs
  1315. )
  1316. self._stages_forward_initialized = True
  1317. if self._has_backward and not self._stages_backward_initialized:
  1318. for stage in self._stages:
  1319. stage._prepare_backward_infra(self._n_microbatches)
  1320. self._stages_backward_initialized = True
  1321. def _validate_and_set_stage_mapping(
  1322. self, actions: dict[int, list[_Action | None]]
  1323. ) -> None:
  1324. """
  1325. Allocates the stage index to rank mapping which is needed for communication
  1326. """
  1327. self.stage_index_to_group_rank = _validate_schedule(
  1328. actions,
  1329. self.pp_group_size,
  1330. self._num_stages,
  1331. self._n_microbatches,
  1332. )
  1333. for stage in self._stages:
  1334. stage.stage_index_to_group_rank = self.stage_index_to_group_rank
  1335. def _dump_csv(self, filename):
  1336. """Dump a CSV representation of the schedule into a file with the provided filename."""
  1337. with open(filename, "w", newline="") as csvfile:
  1338. writer = csv.writer(csvfile)
  1339. for rank in self.pipeline_order:
  1340. writer.writerow(self.pipeline_order[rank])
  1341. def _load_csv(self, filename, format="compute_only"):
  1342. """Load a CSV representation of the schedule from a file with the provided filename.
  1343. This API will most likely get renamed/refactored so is marked as internal for now.
  1344. format must be "compute_only" for PipelineScheduleMulti.
  1345. """
  1346. assert format == "compute_only"
  1347. with open(filename, newline="") as csvfile:
  1348. reader = csv.reader(csvfile)
  1349. for rank, row in enumerate(reader):
  1350. self.pipeline_order[rank] = [_Action.from_str(s) for s in row]
  1351. # Validates the order of the pipeline actions and infers the stage_to_rank_mapping.
  1352. # This will overwrite the default stage_to_rank_mapping created in the constructor
  1353. self._validate_and_set_stage_mapping(self.pipeline_order)
  1354. def step(
  1355. self,
  1356. *args,
  1357. target=None,
  1358. losses: list | None = None,
  1359. return_outputs: bool = True,
  1360. **kwargs,
  1361. ):
  1362. """
  1363. Run one iteration of the pipeline schedule with *whole-batch* input.
  1364. Will chunk the input into microbatches automatically, and go through the
  1365. microbatches according to the schedule implementation.
  1366. args: positional arguments to the model (as in non-pipeline case).
  1367. kwargs: keyword arguments to the model (as in non-pipeline case).
  1368. target: target for the loss function.
  1369. losses: a list to store the losses for each microbatch.
  1370. return_outputs: whether to return the outputs from the last stage.
  1371. """
  1372. if (
  1373. self._has_backward
  1374. and self._backward_requires_autograd
  1375. and not torch.is_grad_enabled()
  1376. ):
  1377. raise RuntimeError(
  1378. "step() requires gradients to be enabled for backward computation; "
  1379. "it should not be used under torch.no_grad() context. "
  1380. "Please call eval() instead."
  1381. )
  1382. # Set the same has_backward flag for stage object
  1383. for stage in self._stages:
  1384. stage.has_backward = self._has_backward
  1385. # Clean per iteration
  1386. for stage in self._stages:
  1387. stage.clear_runtime_states()
  1388. # Split inputs into microbatches
  1389. args_split, kwargs_split = self._split_inputs(args, kwargs)
  1390. # Split target into microbatches
  1391. if target is not None:
  1392. targets_split = list(torch.tensor_split(target, self._n_microbatches))
  1393. else:
  1394. targets_split = None
  1395. # Run microbatches
  1396. self._step_microbatches(
  1397. args_split, kwargs_split, targets_split, losses, return_outputs
  1398. )
  1399. # Return merged results per original format
  1400. for stage in self._stages:
  1401. if stage.is_last and return_outputs:
  1402. return self._merge_outputs(stage.output_chunks)
  1403. # Does not contain the last stage or we do not return output chunks
  1404. return None
  1405. def _step_microbatches(
  1406. self,
  1407. arg_mbs: list | None = None,
  1408. kwarg_mbs: list | None = None,
  1409. target_mbs: list | None = None,
  1410. losses: list | None = None,
  1411. return_outputs: bool = True,
  1412. ):
  1413. """
  1414. Operate on the microbatches for looped schedules (multiple stages on each rank).
  1415. TODO: Does not use sorted_batch_isend_irecv(). As a result, this schedule does
  1416. not support models with skip connections.
  1417. """
  1418. arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
  1419. self._initialize_stages(arg_mbs[0], kwarg_mbs[0])
  1420. # Based on the plan in Step 1 created in __init__:
  1421. # 2. Perform communication based on the pipeline_order
  1422. stage_index_to_stage: dict[int, _PipelineStageBase] = {
  1423. stage.stage_index: stage for stage in self._stages
  1424. }
  1425. # determine prev_rank and next_rank based on which ranks are next to
  1426. # the stages in the pipeline_order
  1427. all_prev_ranks: set[int] = set()
  1428. all_next_ranks: set[int] = set()
  1429. for stage_index in stage_index_to_stage:
  1430. # TODO: assumption that stages only communicate from distances of +1/-1 (no skip connections)
  1431. if stage_index > 0:
  1432. all_prev_ranks.add(self.stage_index_to_group_rank[stage_index - 1])
  1433. if stage_index < self._num_stages - 1:
  1434. all_next_ranks.add(self.stage_index_to_group_rank[stage_index + 1])
  1435. # count either full_backward or backward_weight together, to determine when to sync DP grads
  1436. backward_counter: Counter[int] = Counter()
  1437. for time_step, action in enumerate(self.pipeline_order[self.rank]):
  1438. try:
  1439. ops: list[dist.P2POp] = []
  1440. if action is not None:
  1441. computation_type = action.computation_type
  1442. mb_index = action.microbatch_index
  1443. stage_index = action.stage_index
  1444. assert mb_index is not None, (
  1445. "All currently supported action types require valid microbatch_index"
  1446. )
  1447. if computation_type == _ComputationType.FORWARD:
  1448. # perform forward computation
  1449. stage = stage_index_to_stage[stage_index]
  1450. output = stage.forward_one_chunk(
  1451. mb_index,
  1452. arg_mbs[mb_index],
  1453. kwarg_mbs[mb_index],
  1454. save_forward_output=return_outputs,
  1455. )
  1456. self._maybe_compute_loss(stage, output, target_mbs, mb_index)
  1457. ops.extend(stage.get_fwd_send_ops(mb_index))
  1458. elif computation_type == _ComputationType.FULL_BACKWARD:
  1459. # perform backward computation
  1460. stage = stage_index_to_stage[stage_index]
  1461. loss = self._maybe_get_loss(stage, mb_index)
  1462. backward_counter[stage_index] += 1
  1463. last_backward = (
  1464. backward_counter[stage_index] == self._n_microbatches
  1465. )
  1466. grad_scale_factor = (
  1467. self._n_microbatches if self.scale_grads else 1
  1468. )
  1469. stage.backward_one_chunk(
  1470. mb_index,
  1471. loss=loss,
  1472. full_backward=True,
  1473. last_backward=last_backward,
  1474. )
  1475. if last_backward:
  1476. stage.scale_grads(grad_scale_factor)
  1477. ops.extend(stage.get_bwd_send_ops(mb_index))
  1478. elif computation_type == _ComputationType.BACKWARD_INPUT:
  1479. # perform backward computation
  1480. stage = stage_index_to_stage[stage_index]
  1481. loss = self._maybe_get_loss(stage, mb_index)
  1482. stage.backward_one_chunk(
  1483. mb_index,
  1484. loss=loss,
  1485. full_backward=False,
  1486. last_backward=False,
  1487. )
  1488. ops.extend(stage.get_bwd_send_ops(mb_index))
  1489. elif computation_type == _ComputationType.BACKWARD_WEIGHT:
  1490. # perform weight update
  1491. stage = stage_index_to_stage[stage_index]
  1492. backward_counter[stage_index] += 1
  1493. last_backward = (
  1494. backward_counter[stage_index] == self._n_microbatches
  1495. )
  1496. grad_scale_factor = (
  1497. self._n_microbatches if self.scale_grads else 1
  1498. )
  1499. stage.backward_weight_one_chunk(
  1500. mb_index,
  1501. last_backward=last_backward,
  1502. )
  1503. if last_backward:
  1504. stage.scale_grads(grad_scale_factor)
  1505. else:
  1506. raise ValueError(f"Unknown computation type {computation_type}")
  1507. # Look at the neighboring ranks for this current timestep and determine whether
  1508. # this current rank needs to do any recv communication
  1509. for prev_rank in all_prev_ranks:
  1510. prev_rank_ops = self.pipeline_order[prev_rank]
  1511. prev_rank_action = None
  1512. if time_step < len(prev_rank_ops):
  1513. prev_rank_action = prev_rank_ops[time_step]
  1514. if prev_rank_action is not None:
  1515. computation_type = prev_rank_action.computation_type
  1516. mb_index = prev_rank_action.microbatch_index
  1517. stage_index = prev_rank_action.stage_index
  1518. assert mb_index is not None, (
  1519. "All currently supported action types require valid microbatch_index"
  1520. )
  1521. # Only handle sends for the forward from a previous rank
  1522. if computation_type == _ComputationType.FORWARD:
  1523. # If not the last stage, then receive fwd activations
  1524. if stage_index + 1 in stage_index_to_stage:
  1525. # TODO: We are assuming that stage will always receive from stage-1
  1526. # however that is not necessarily true of get_fwd_recv_ops
  1527. stage = stage_index_to_stage[stage_index + 1]
  1528. ops.extend(stage.get_fwd_recv_ops(mb_index))
  1529. elif computation_type in (
  1530. FULL_BACKWARD,
  1531. BACKWARD_INPUT,
  1532. BACKWARD_WEIGHT,
  1533. ):
  1534. # Previous rank doing backward has no influence for the current rank forward recv
  1535. pass
  1536. else:
  1537. raise ValueError(
  1538. f"Unknown computation type {computation_type}"
  1539. )
  1540. for next_rank in all_next_ranks:
  1541. next_rank_ops = self.pipeline_order[next_rank]
  1542. next_rank_action = None
  1543. if time_step < len(next_rank_ops):
  1544. next_rank_action = next_rank_ops[time_step]
  1545. if next_rank_action is not None:
  1546. computation_type = next_rank_action.computation_type
  1547. mb_index = next_rank_action.microbatch_index
  1548. stage_index = next_rank_action.stage_index
  1549. assert mb_index is not None, (
  1550. "All currently supported action types require valid microbatch_index"
  1551. )
  1552. # Only handle receives for the backwards from a next rank
  1553. if computation_type in (FORWARD, BACKWARD_WEIGHT):
  1554. # Next rank doing forward or weight update has no influence for the current rank backward recv
  1555. pass
  1556. elif computation_type in (BACKWARD_INPUT, FULL_BACKWARD):
  1557. # If not the first stage, then receive bwd gradients
  1558. if stage_index - 1 in stage_index_to_stage:
  1559. # TODO: We are assuming that stage will always receive from stage+1
  1560. # however that is not necessarily true of get_bwd_recv_ops
  1561. stage = stage_index_to_stage[stage_index - 1]
  1562. ops.extend(stage.get_bwd_recv_ops(mb_index))
  1563. else:
  1564. raise ValueError(
  1565. f"Unknown computation type {computation_type}"
  1566. )
  1567. # do the communication
  1568. _wait_batch_p2p(_batch_p2p(ops))
  1569. except Exception as e:
  1570. logger.error( # noqa: G200
  1571. "[Rank %s] pipeline schedule %s caught the following exception '%s' \
  1572. at time_step %s when running action %s",
  1573. self.rank,
  1574. self.__class__.__name__,
  1575. str(e),
  1576. time_step,
  1577. action,
  1578. )
  1579. logger.error(
  1580. "%s",
  1581. _format_pipeline_order(
  1582. self.pipeline_order, error_step_number=time_step
  1583. ),
  1584. )
  1585. raise e
  1586. # Return losses if there is a container passed in
  1587. self._update_losses(self._stages, losses)
  1588. class _PipelineContext:
  1589. def __init__(
  1590. self,
  1591. schedule_ref: _PipelineSchedule,
  1592. arg_mbs: list[tuple] | None = None,
  1593. kwarg_mbs: list[dict] | None = None,
  1594. target_mbs: list | None = None,
  1595. losses: list | None = None,
  1596. ):
  1597. self.schedule_ref = schedule_ref
  1598. self.arg_mbs = arg_mbs
  1599. self.kwarg_mbs = kwarg_mbs
  1600. self.target_mbs = target_mbs
  1601. self.losses = losses
  1602. class _CustomFunctionProtocol(Protocol):
  1603. def __call__(self, action: _Action, ctx: _PipelineContext) -> None: ...
  1604. class _PipelineScheduleRuntime(PipelineScheduleMulti):
  1605. """
  1606. Provides a simple runtime that requires a 'schedule IR' including specified communication operations.
  1607. Can be instantiated directly by creating _PipelineScheduleRuntime and calling load_csv, or can be
  1608. subclassed and the subclass can be responsible for creating a schedule IR.
  1609. """
  1610. def __init__(self, *args, **kwargs):
  1611. super().__init__(*args, **kwargs)
  1612. # Action to custom function mapping
  1613. self._comp_type_to_function_map: dict[_ComputationType, Callable] = {}
  1614. # count either full_backward or backward_weight together, to determine when to sync DP grads
  1615. self.backward_counter: Counter[int] = Counter()
  1616. # recv ops indexed by (stage_idx, mb_idx) need to be waited on before use
  1617. self.bwd_recv_ops: dict[tuple[int, int], list[dist.Work]] = {}
  1618. self.fwd_recv_ops: dict[tuple[int, int], list[dist.Work]] = {}
  1619. # we track which stages are 'active' when used with FSDP, and wait on unshard ops before computing on stages
  1620. self.unshard_ops: dict[int, list[UnshardHandle]] = defaultdict(list)
  1621. self.unsharded_stages = set()
  1622. def register_custom_function(
  1623. self,
  1624. computation_type: _ComputationType,
  1625. custom_function: _CustomFunctionProtocol,
  1626. ) -> None:
  1627. """
  1628. Register a custom function to be executed for a specific computation type.
  1629. Args:
  1630. computation_type: The computation type for which to register the custom function
  1631. custom_function: The function to execute when this computation type is encountered.
  1632. Must have signature: (action: _Action, ctx: _PipelineContext) -> None
  1633. """
  1634. # Ensure that the computation type is valid
  1635. if computation_type not in (
  1636. FORWARD,
  1637. FULL_BACKWARD,
  1638. BACKWARD_INPUT,
  1639. BACKWARD_WEIGHT,
  1640. OVERLAP_F_B,
  1641. UNSHARD,
  1642. RESHARD,
  1643. REDUCE_GRAD,
  1644. ):
  1645. raise ValueError(
  1646. f"Invalid computation type {computation_type}. Only FORWARD, FULL_BACKWARD, \
  1647. BACKWARD_INPUT, BACKWARD_WEIGHT, OVERLAP_F_B, UNSHARD, RESHARD and REDUCE_GRAD are supported."
  1648. )
  1649. # Check if computation_type is already registered
  1650. if computation_type in self._comp_type_to_function_map:
  1651. logger.warning(
  1652. "Computation type %s is already registered. "
  1653. "Overwriting the existing custom function.",
  1654. computation_type,
  1655. )
  1656. self._comp_type_to_function_map[computation_type] = custom_function
  1657. def _prepare_schedule_with_comms(
  1658. self,
  1659. actions: dict[int, list[_Action | None]],
  1660. format: str = "compute_only",
  1661. ):
  1662. """
  1663. Given an in-memory representation for a simple compute-only schedule, lower it to a complex schedule including
  1664. communication actions. Stores the schedule in self, and must be called before running step_mo()
  1665. """
  1666. # validate the provided actions are valid and overrides the default stage_index_to_group_rank
  1667. super()._validate_and_set_stage_mapping(actions)
  1668. self.pipeline_order_with_comms: dict[int, list[_Action]] = {}
  1669. if format == "compute_comms":
  1670. for rank in actions:
  1671. self.pipeline_order_with_comms[rank] = []
  1672. for action in actions[rank]:
  1673. assert action is not None
  1674. self.pipeline_order_with_comms[rank].append(action)
  1675. # TODO what level of validation should we offer for compute+comms schedule?
  1676. elif format == "compute_only":
  1677. # Validate that the schedule does not have comms already added to it
  1678. for rank, action_list in actions.items():
  1679. for i, action in enumerate(action_list):
  1680. if action is not None and not action.is_compute_op:
  1681. raise ValueError(
  1682. f"Expected compute-only schedule but found communication action "
  1683. f"'{action}' at rank {rank}, position {i}. "
  1684. f"Communication actions (e.g. SEND_F, RECV_F, etc.) "
  1685. f"should not be present when format='compute_only'."
  1686. )
  1687. # Perform schedule lowering
  1688. for rank in actions:
  1689. self.pipeline_order_with_comms[rank] = _add_unshard_reshard(
  1690. actions[rank]
  1691. )
  1692. self.pipeline_order_with_comms[rank] = _add_reduce_grad( # type: ignore[assignment]
  1693. self.pipeline_order_with_comms[rank], # type: ignore[arg-type]
  1694. self._n_microbatches,
  1695. )
  1696. self.pipeline_order_with_comms = _add_send_recv(
  1697. self.pipeline_order_with_comms,
  1698. stage_to_rank=lambda s: self.stage_index_to_group_rank[s],
  1699. num_stages=self._num_stages,
  1700. )
  1701. else:
  1702. raise NotImplementedError(f"{format=} is not implemented")
  1703. def _load_csv(self, filename: str, format: str = "compute_only"):
  1704. """Loads a csv in simple format and then lowers it to include communication actions
  1705. format must be either "compute_only" or "compute_comms". If compute_only, the lowering passes
  1706. will automatically be run to generate a compute_comms schedule.
  1707. """
  1708. if format == "compute_only":
  1709. # this will populate self.pipeline_order
  1710. super()._load_csv(filename)
  1711. # this will populate self.pipeline_order_with_comms
  1712. self._prepare_schedule_with_comms(self.pipeline_order)
  1713. elif format == "compute_comms":
  1714. actions = {}
  1715. with open(filename, newline="") as csvfile:
  1716. reader = csv.reader(csvfile)
  1717. for rank, row in enumerate(reader):
  1718. actions[rank] = [_Action.from_str(s) for s in row]
  1719. self._prepare_schedule_with_comms(actions, format=format)
  1720. else:
  1721. raise NotImplementedError(f"{format=} is not implemented")
  1722. def _dump_csv(self, filename: str, format: str = "compute_comms"):
  1723. """Dump a CSV representation of the schedule into a file with the provided filename."""
  1724. if format == "compute_only":
  1725. assert self.pipeline_order is not None, (
  1726. "Compute only schedule must be available"
  1727. )
  1728. with open(filename, "w", newline="") as csvfile:
  1729. writer = csv.writer(csvfile)
  1730. for rank in self.pipeline_order:
  1731. writer.writerow(self.pipeline_order[rank])
  1732. elif format == "compute_comms":
  1733. assert self.pipeline_order_with_comms is not None, (
  1734. "Must initialize compute_comms schedule before dump_csv"
  1735. )
  1736. with open(filename, "w", newline="") as csvfile:
  1737. writer = csv.writer(csvfile)
  1738. for rank in self.pipeline_order_with_comms:
  1739. writer.writerow(self.pipeline_order_with_comms[rank])
  1740. def _simulate(self):
  1741. return _simulate_comms_compute(
  1742. self.pipeline_order_with_comms,
  1743. lambda s: self.stage_index_to_group_rank[s],
  1744. self._num_stages,
  1745. )
  1746. def _assert_unsharded(self, stage: _PipelineStageBase):
  1747. """If an unshard is active for `stage_idx`, wait() it and mark `stage_idx` unshared."""
  1748. stage_uses_fsdp = isinstance(stage.submod, FSDPModule)
  1749. if stage_uses_fsdp:
  1750. stage_idx = stage.stage_index
  1751. if stage_idx in self.unshard_ops:
  1752. for op in self.unshard_ops[stage_idx]:
  1753. op.wait()
  1754. del self.unshard_ops[stage_idx]
  1755. self.unsharded_stages.add(stage_idx)
  1756. assert stage_idx in self.unsharded_stages, (
  1757. f"Attempted to compute on sharded {stage_idx=}"
  1758. )
  1759. def _step_microbatches(
  1760. self,
  1761. arg_mbs: list | None = None,
  1762. kwarg_mbs: list | None = None,
  1763. target_mbs: list | None = None,
  1764. losses: list | None = None,
  1765. return_outputs: bool = True,
  1766. ):
  1767. """
  1768. Operate on the microbatches for looped schedules (multiple stages on each rank).
  1769. TODO: Does not use sorted_batch_isend_irecv(). As a result, this schedule does
  1770. not support models with skip connections.
  1771. """
  1772. arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
  1773. self._initialize_stages(arg_mbs[0], kwarg_mbs[0])
  1774. # Based on the plan in Step 1 created in __init__:
  1775. # 2. Perform communication based on the pipeline_order
  1776. stage_index_to_stage: dict[int, _PipelineStageBase] = {
  1777. stage.stage_index: stage for stage in self._stages
  1778. }
  1779. assert self.pipeline_order_with_comms is not None, (
  1780. "Must call _prepare_schedule_with_comms() before calling _step_microbatches()"
  1781. )
  1782. # send ops should be waited on before step() exists, mainly for hygiene
  1783. send_ops: list[list[dist.Work]] = []
  1784. def _perform_action(action: _Action) -> None:
  1785. comp_type = action.computation_type
  1786. mb_index: int = (
  1787. action.microbatch_index if action.microbatch_index is not None else -1
  1788. )
  1789. assert mb_index >= 0 or comp_type in (
  1790. UNSHARD,
  1791. RESHARD,
  1792. REDUCE_GRAD,
  1793. ), f"{action=} missing mb_index"
  1794. stage_idx = action.stage_index
  1795. stage = stage_index_to_stage[stage_idx]
  1796. stage_uses_fsdp = isinstance(stage.submod, FSDPModule)
  1797. # see [Note: V-schedule special case]
  1798. is_next_stage_on_this_rank = stage_idx + 1 in stage_index_to_stage
  1799. is_prev_stage_on_this_rank = stage_idx - 1 in stage_index_to_stage
  1800. # TODO(whc) it's not actually safe to use _batch_p2p here in the uncommon case the model has skip-connections,
  1801. # since we do not want to batch up ops between more than a pair of ranks. _sorted_batch_p2p would be
  1802. # safe to use instead.
  1803. # However, I was wondering if I should avoid calling batched operators at all in the case that there is
  1804. # only one operator per batch. I could iterate through the 'fwd_send_ops' one by one and run them.
  1805. if comp_type == SEND_F:
  1806. send_ops.append(_batch_p2p(stage.get_fwd_send_ops(mb_index)))
  1807. elif comp_type == SEND_B:
  1808. send_ops.append(_batch_p2p(stage.get_bwd_send_ops(mb_index)))
  1809. elif comp_type == RECV_F:
  1810. assert (
  1811. stage_idx,
  1812. mb_index,
  1813. ) not in self.fwd_recv_ops, (
  1814. f"Recv twice for {stage_idx=} {mb_index=} without executing forward"
  1815. )
  1816. self.fwd_recv_ops[(stage_idx, mb_index)] = _batch_p2p(
  1817. stage.get_fwd_recv_ops(mb_index)
  1818. )
  1819. elif comp_type == RECV_B:
  1820. assert (
  1821. stage_idx,
  1822. mb_index,
  1823. ) not in self.bwd_recv_ops, (
  1824. f"Recv twice for {stage_idx=} {mb_index=} without executing backward"
  1825. )
  1826. self.bwd_recv_ops[(stage_idx, mb_index)] = _batch_p2p(
  1827. stage.get_bwd_recv_ops(mb_index)
  1828. )
  1829. elif comp_type == UNSHARD:
  1830. if stage_uses_fsdp:
  1831. assert (
  1832. stage_idx not in self.unsharded_stages
  1833. and stage_idx not in self.unshard_ops
  1834. ), f"Unsharding the same {stage_idx=} twice"
  1835. for submodule in stage.submod.modules():
  1836. if not isinstance(submodule, FSDPModule):
  1837. continue
  1838. handle = cast(UnshardHandle, submodule.unshard(async_op=True))
  1839. self.unshard_ops[stage_idx].append(handle)
  1840. elif comp_type == RESHARD:
  1841. if stage_uses_fsdp:
  1842. assert stage_idx in self.unsharded_stages, (
  1843. f"Resharding {stage_idx=} without unsharding"
  1844. )
  1845. assert stage_idx not in self.unshard_ops, (
  1846. f"Resharding {stage_idx=} before finishing unshard"
  1847. )
  1848. for submodule in stage.submod.modules():
  1849. if not isinstance(submodule, FSDPModule):
  1850. continue
  1851. submodule.reshard()
  1852. self.unsharded_stages.remove(stage_idx)
  1853. elif comp_type == FORWARD:
  1854. self._assert_unsharded(stage)
  1855. if (
  1856. not stage.is_first
  1857. # no recv op expected for V-schedule special case (see [Note: V-schedule special case])
  1858. and not is_prev_stage_on_this_rank
  1859. ):
  1860. assert (
  1861. stage_idx,
  1862. mb_index,
  1863. ) in self.fwd_recv_ops, (
  1864. f"Computing {action=} before receiving input"
  1865. )
  1866. _wait_batch_p2p(self.fwd_recv_ops.pop((stage_idx, mb_index)))
  1867. output = stage.forward_one_chunk(
  1868. mb_index,
  1869. arg_mbs[mb_index], # type: ignore[index]
  1870. kwarg_mbs[mb_index], # type: ignore[index]
  1871. save_forward_output=return_outputs,
  1872. )
  1873. self._maybe_compute_loss(stage, output, target_mbs, mb_index)
  1874. # SEND/RECV op are avoided for special case with 2 adjacent stages on same rank
  1875. # see [Note: V-schedule special case]
  1876. if is_next_stage_on_this_rank:
  1877. stage_index_to_stage[stage_idx + 1].set_local_fwd_input(
  1878. output, mb_index
  1879. )
  1880. elif comp_type == FULL_BACKWARD:
  1881. self._assert_unsharded(stage)
  1882. if (
  1883. not stage.is_last
  1884. # no recv op expected for V-schedule special case (see [Note: V-schedule special case])
  1885. and not is_next_stage_on_this_rank
  1886. ):
  1887. assert (
  1888. stage_idx,
  1889. mb_index,
  1890. ) in self.bwd_recv_ops, (
  1891. f"Attempted to run compute {action=} before receiving input"
  1892. )
  1893. _wait_batch_p2p(self.bwd_recv_ops.pop((stage_idx, mb_index)))
  1894. loss = self._maybe_get_loss(stage, mb_index)
  1895. self.backward_counter[stage_idx] += 1
  1896. last_backward = self.backward_counter[stage_idx] == self._n_microbatches
  1897. stage.backward_one_chunk(
  1898. mb_index,
  1899. loss=loss,
  1900. full_backward=True,
  1901. last_backward=last_backward,
  1902. )
  1903. # SEND/RECV op are avoided for special case with 2 adjacent stages on same rank
  1904. # see [Note: V-schedule special case]
  1905. if is_prev_stage_on_this_rank:
  1906. stage_index_to_stage[stage_idx - 1].set_local_bwd_input(
  1907. stage.get_local_bwd_output(mb_index), mb_index
  1908. )
  1909. elif comp_type == BACKWARD_INPUT:
  1910. self._assert_unsharded(stage)
  1911. if not stage.is_last and not is_next_stage_on_this_rank:
  1912. assert (
  1913. stage_idx,
  1914. mb_index,
  1915. ) in self.bwd_recv_ops, (
  1916. f"Attempted to run compute {action=} before receiving input"
  1917. )
  1918. _wait_batch_p2p(self.bwd_recv_ops.pop((stage_idx, mb_index)))
  1919. loss = self._maybe_get_loss(stage, mb_index)
  1920. stage.backward_one_chunk(
  1921. mb_index,
  1922. loss=loss,
  1923. full_backward=False,
  1924. last_backward=False,
  1925. )
  1926. # SEND/RECV op are avoided for special case with 2 adjacent stages on same rank
  1927. # see [Note: V-schedule special case]
  1928. if is_prev_stage_on_this_rank:
  1929. stage_index_to_stage[stage_idx - 1].set_local_bwd_input(
  1930. stage.get_local_bwd_output(mb_index), mb_index
  1931. )
  1932. elif comp_type == BACKWARD_WEIGHT:
  1933. self._assert_unsharded(stage)
  1934. self.backward_counter[stage_idx] += 1
  1935. last_backward = self.backward_counter[stage_idx] == self._n_microbatches
  1936. stage.backward_weight_one_chunk(
  1937. mb_index,
  1938. last_backward=last_backward,
  1939. )
  1940. elif comp_type == REDUCE_GRAD:
  1941. grad_scale_factor = self._n_microbatches if self.scale_grads else 1
  1942. stage.perform_reduce_grad(grad_scale_factor)
  1943. else:
  1944. raise ValueError(f"{action=} is unknown or unsupported")
  1945. # count either full_backward or backward_weight together, to determine when to sync DP grads
  1946. self.backward_counter.clear()
  1947. for time_step, action in enumerate(self.pipeline_order_with_comms[self.rank]):
  1948. logger.debug(
  1949. "_PipelineScheduleRuntime running time_step %d, action %s",
  1950. time_step,
  1951. action,
  1952. )
  1953. try:
  1954. with record_function(_get_profiler_function_name(action)):
  1955. if action.computation_type in self._comp_type_to_function_map:
  1956. ctx = _PipelineContext(
  1957. self,
  1958. arg_mbs,
  1959. kwarg_mbs,
  1960. target_mbs,
  1961. losses,
  1962. )
  1963. self._comp_type_to_function_map[action.computation_type](
  1964. action, ctx
  1965. )
  1966. elif action.computation_type == OVERLAP_F_B:
  1967. assert action.sub_actions is not None, "sub_actions must be set"
  1968. for sub_a in action.sub_actions:
  1969. _perform_action(sub_a)
  1970. else:
  1971. _perform_action(action)
  1972. except Exception as e:
  1973. logger.error(
  1974. "_PipelineScheduleRuntime caught exception at step %s when running action %s. Full Schedule:",
  1975. time_step,
  1976. action,
  1977. )
  1978. logger.error(
  1979. _format_pipeline_order(
  1980. self.pipeline_order_with_comms, # type: ignore[arg-type]
  1981. error_step_number=time_step,
  1982. )
  1983. )
  1984. raise e
  1985. # Mostly these operations should have finished long ago, but there isn't an obvious time when to wait for them
  1986. while send_ops:
  1987. _wait_batch_p2p(send_ops.pop())
  1988. assert len(self.unshard_ops) == 0, "Unused unshard operations"
  1989. # Return losses if there is a container passed in
  1990. self._update_losses(self._stages, losses)
  1991. class ScheduleLoopedBFS(_PipelineScheduleRuntime):
  1992. """
  1993. Breadth-First Pipeline Parallelism.
  1994. See https://arxiv.org/abs/2211.05953 for details.
  1995. Similar to Interleaved 1F1B, Looped BFS supports multiple stages per rank.
  1996. What is different is that when microbatches are ready for multiple local
  1997. stages, Loops BFS will prioritizes the earlier stage, running all available
  1998. microbatches at once.
  1999. """
  2000. def __init__(
  2001. self,
  2002. stages: list[_PipelineStageBase],
  2003. n_microbatches: int,
  2004. loss_fn: Callable | _Loss | None = None,
  2005. output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
  2006. scale_grads: bool = True,
  2007. backward_requires_autograd: bool = True,
  2008. ):
  2009. super().__init__(
  2010. stages=stages,
  2011. n_microbatches=n_microbatches,
  2012. loss_fn=loss_fn,
  2013. output_merge_spec=output_merge_spec,
  2014. scale_grads=scale_grads,
  2015. backward_requires_autograd=backward_requires_autograd,
  2016. )
  2017. # 1. Create the pipeline_order (all ranks do this calculation)
  2018. # This will be used to keep track of the current state of the entire pipeline
  2019. # pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
  2020. self.pipeline_order: dict[int, list[_Action | None]] = {}
  2021. # ========================================================================
  2022. for rank in range(self.pp_group_size):
  2023. rank_ops = self._calculate_single_rank_operations(rank)
  2024. self.pipeline_order[rank] = rank_ops
  2025. # Initialize the pipeline order with communication necessary to run with _PipelineScheduleRuntime
  2026. self._prepare_schedule_with_comms(self.pipeline_order)
  2027. def _calculate_single_rank_operations(self, rank):
  2028. n_local_stages = len(self._stages)
  2029. stage_indices = range(
  2030. rank, self.pp_group_size * n_local_stages, self.pp_group_size
  2031. )
  2032. # Store the list of operations used for that rank
  2033. # Pre-padding, rank starts with no-ops based on the warmup.
  2034. rank_ops: list[_Action | None] = [None for _ in range(rank)]
  2035. for stage_index in stage_indices:
  2036. rank_ops.extend(
  2037. _Action(stage_index, _ComputationType.FORWARD, mb_index)
  2038. for mb_index in range(self._n_microbatches)
  2039. )
  2040. # wait for the first backward to trickle up
  2041. # which is 2 for every hop away
  2042. post_warmup_ops = 2 * (self.pp_group_size - 1 - rank)
  2043. rank_ops.extend([None] * post_warmup_ops)
  2044. for stage_index in reversed(stage_indices):
  2045. rank_ops.extend(
  2046. _Action(stage_index, _ComputationType.FULL_BACKWARD, mb_index)
  2047. for mb_index in reversed(range(self._n_microbatches))
  2048. )
  2049. return rank_ops
  2050. def _get_1f1b_rank_ops(
  2051. n_local_stages,
  2052. pp_group_size,
  2053. warmup_ops,
  2054. fwd_bwd_ops,
  2055. cooldown_ops,
  2056. rank,
  2057. forward_stage_index,
  2058. backward_stage_index,
  2059. num_1f1b_microbatches=0,
  2060. enable_zero_bubble=False,
  2061. ):
  2062. # All stages start with handling microbatch 0
  2063. fwd_stage_mb_index: dict[int, int] = defaultdict(int)
  2064. bwd_stage_mb_index: dict[int, int] = defaultdict(int)
  2065. weight_stage_mb_index: dict[int, int] = defaultdict(int)
  2066. # Store the list of operations used for that rank
  2067. # Pre-padding, rank starts with no-ops based on the warmup.
  2068. rank_ops: list[_Action | None] = [None for _ in range(rank)]
  2069. # These are used to calculate the number of slots to fill with no-ops, to account for the delay in warmup
  2070. # when we want to wait for the backward to trickle back up and start 1f1b to align all ranks.
  2071. # Formula:
  2072. # pre-padding + warmup_ops + post_warmup_ops = earliest time step of first backward
  2073. # post_warmup_ops = [earliest time step of first backward] - (warmup_ops + pre-padding)
  2074. # earliest time step of first backward = [local_stages * group_size + 2 * (group_size - 1 - rank)]
  2075. # warmup_ops = calculated above
  2076. post_warmup_ops = (
  2077. n_local_stages * pp_group_size + 2 * (pp_group_size - 1 - rank)
  2078. ) - (warmup_ops + rank)
  2079. if enable_zero_bubble:
  2080. post_warmup_ops = pp_group_size - rank - 1
  2081. total_ops = warmup_ops + fwd_bwd_ops + cooldown_ops
  2082. backward_op_ids = []
  2083. weight_op_count = 0
  2084. FULL_BACKWARD_OR_BACKWARD_INPUT = (
  2085. BACKWARD_INPUT if enable_zero_bubble else FULL_BACKWARD
  2086. )
  2087. for op in range(total_ops):
  2088. # Warmup phase
  2089. if op < warmup_ops:
  2090. fwd_stage_index = forward_stage_index(op)
  2091. # This will assign the current microbatch index and update it as well
  2092. fwd_stage_mb_index[fwd_stage_index] = (
  2093. mb_index := fwd_stage_mb_index[fwd_stage_index]
  2094. ) + 1
  2095. rank_ops.append(
  2096. _Action(fwd_stage_index, _ComputationType.FORWARD, mb_index)
  2097. )
  2098. if op == warmup_ops - 1:
  2099. # This is the last step in the warmup phase, so we need to wait for the backward to trickle back up
  2100. rank_ops.extend([None] * post_warmup_ops)
  2101. # 1F1B Phase (forward and backward)
  2102. elif warmup_ops <= op < warmup_ops + fwd_bwd_ops:
  2103. fwd_stage_index = forward_stage_index(op)
  2104. fwd_stage_mb_index[fwd_stage_index] = (
  2105. fwd_mb_index := fwd_stage_mb_index[fwd_stage_index]
  2106. ) + 1
  2107. rank_ops.append(
  2108. _Action(fwd_stage_index, _ComputationType.FORWARD, fwd_mb_index)
  2109. )
  2110. bwd_stage_index = backward_stage_index(op)
  2111. bwd_stage_mb_index[bwd_stage_index] = (
  2112. bwd_mb_index := bwd_stage_mb_index[bwd_stage_index]
  2113. ) + 1
  2114. rank_ops.append(
  2115. _Action(bwd_stage_index, FULL_BACKWARD_OR_BACKWARD_INPUT, bwd_mb_index)
  2116. )
  2117. backward_op_ids.append(op)
  2118. if enable_zero_bubble and op - warmup_ops >= num_1f1b_microbatches:
  2119. weight_stage_index = backward_stage_index(
  2120. backward_op_ids[weight_op_count]
  2121. )
  2122. weight_stage_mb_index[weight_stage_index] = (
  2123. weight_mb_index := weight_stage_mb_index[weight_stage_index]
  2124. ) + 1
  2125. rank_ops.append(
  2126. _Action(
  2127. weight_stage_index,
  2128. _ComputationType.BACKWARD_WEIGHT,
  2129. weight_mb_index,
  2130. )
  2131. )
  2132. weight_op_count += 1
  2133. # Cooldown phase
  2134. else:
  2135. # During cooldown phase, we need steps to align with 1f1b happening in other ranks
  2136. # TODO: we don't need to always append, after all 1f1b are finished we can stop appending None
  2137. if not enable_zero_bubble:
  2138. rank_ops.append(None)
  2139. bwd_stage_index = backward_stage_index(op)
  2140. bwd_stage_mb_index[bwd_stage_index] = (
  2141. bwd_mb_index := bwd_stage_mb_index[bwd_stage_index]
  2142. ) + 1
  2143. rank_ops.append(
  2144. _Action(bwd_stage_index, FULL_BACKWARD_OR_BACKWARD_INPUT, bwd_mb_index)
  2145. )
  2146. backward_op_ids.append(op)
  2147. if enable_zero_bubble and op - warmup_ops >= num_1f1b_microbatches:
  2148. weight_stage_index = backward_stage_index(
  2149. backward_op_ids[weight_op_count]
  2150. )
  2151. weight_stage_mb_index[weight_stage_index] = (
  2152. weight_mb_index := weight_stage_mb_index[weight_stage_index]
  2153. ) + 1
  2154. rank_ops.append(
  2155. _Action(
  2156. weight_stage_index,
  2157. _ComputationType.BACKWARD_WEIGHT,
  2158. weight_mb_index,
  2159. )
  2160. )
  2161. weight_op_count += 1
  2162. while enable_zero_bubble and weight_op_count < len(backward_op_ids):
  2163. weight_stage_index = backward_stage_index(backward_op_ids[weight_op_count])
  2164. weight_stage_mb_index[weight_stage_index] = (
  2165. weight_mb_index := weight_stage_mb_index[weight_stage_index]
  2166. ) + 1
  2167. rank_ops.append(
  2168. _Action(
  2169. weight_stage_index, _ComputationType.BACKWARD_WEIGHT, weight_mb_index
  2170. )
  2171. )
  2172. weight_op_count += 1
  2173. return rank_ops
  2174. class ScheduleInterleaved1F1B(_PipelineScheduleRuntime):
  2175. """
  2176. The Interleaved 1F1B schedule.
  2177. See https://arxiv.org/pdf/2104.04473 for details.
  2178. Will perform one forward and one backward on the microbatches in steady
  2179. state and supports multiple stages per rank. When microbatches are ready for
  2180. multiple local stages, Interleaved 1F1B prioritizes the earlier microbatch
  2181. (also called "depth first").
  2182. This schedule is mostly similar to the original paper.
  2183. It differs by being relaxing the requirement of num_microbatch % pp_size == 0.
  2184. Using the flex_pp schedule, we will have num_rounds = max(1, n_microbatches // pp_group_size) and
  2185. it works as long as n_microbatches % num_rounds is 0. As a few examples, support
  2186. 1. pp_group_size = 4, n_microbatches = 10. We will have num_rounds = 2 and n_microbatches % 2 is 0.
  2187. 2. pp_group_size = 4, n_microbatches = 3. We will have num_rounds = 1 and n_microbatches % 1 is 0.
  2188. """
  2189. def __init__(
  2190. self,
  2191. stages: list[_PipelineStageBase],
  2192. n_microbatches: int,
  2193. loss_fn: Callable | None = None,
  2194. args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
  2195. kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
  2196. output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
  2197. scale_grads: bool = True,
  2198. backward_requires_autograd: bool = True,
  2199. ):
  2200. self.pp_group_size = stages[0].group_size
  2201. super().__init__(
  2202. stages=stages,
  2203. n_microbatches=n_microbatches,
  2204. loss_fn=loss_fn,
  2205. args_chunk_spec=args_chunk_spec,
  2206. kwargs_chunk_spec=kwargs_chunk_spec,
  2207. output_merge_spec=output_merge_spec,
  2208. scale_grads=scale_grads,
  2209. backward_requires_autograd=backward_requires_autograd,
  2210. )
  2211. self.n_local_stages = len(stages)
  2212. self.rank = stages[0].group_rank
  2213. self.number_of_rounds = max(1, n_microbatches // self.pp_group_size)
  2214. self.microbatches_per_round = n_microbatches // self.number_of_rounds
  2215. if n_microbatches % self.number_of_rounds != 0:
  2216. raise ValueError(
  2217. "Interleaved 1F1B requires the number of microbatches to be a "
  2218. f"multiple of the number of rounds ({self.number_of_rounds}), "
  2219. f"but got {n_microbatches}."
  2220. )
  2221. # 1. Create the pipeline_order (all ranks do this calculation)
  2222. # This will be used to keep track of the current state of the entire pipeline
  2223. # pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
  2224. self.pipeline_order: dict[int, list[_Action | None]] = {}
  2225. for rank in range(self.pp_group_size):
  2226. rank_ops = self._calculate_single_rank_operations(rank)
  2227. self.pipeline_order[rank] = rank_ops
  2228. # Initialize the pipeline order with communication necessary to run with _PipelineScheduleRuntime
  2229. self._prepare_schedule_with_comms(self.pipeline_order)
  2230. def _calculate_single_rank_operations(self, rank) -> list[_Action | None]:
  2231. def get_rank_warmup_ops(rank):
  2232. # Warms up operations for last stage
  2233. warmups_ops_last_stage = (
  2234. self.n_local_stages - 1
  2235. ) * self.microbatches_per_round
  2236. # Increment warmup operations by 2 for each hop away from the last stage
  2237. multiply_factor = 2
  2238. warmup_ops = warmups_ops_last_stage + multiply_factor * (
  2239. (self.pp_group_size - 1) - rank
  2240. )
  2241. # We cannot have more warmup operations than there are number of microbatches, so cap it there
  2242. return min(warmup_ops, self._n_microbatches * self.n_local_stages)
  2243. warmup_ops = get_rank_warmup_ops(rank)
  2244. microbatch_ops = self.n_local_stages * self._n_microbatches
  2245. # fwd_bwd_ops should encompass the remaining forwards
  2246. fwd_bwd_ops = microbatch_ops - warmup_ops
  2247. # cooldown_ops should encompass the remaining backwards
  2248. cooldown_ops = microbatch_ops - fwd_bwd_ops
  2249. # total ops encompass both forward and backward ops
  2250. total_ops = warmup_ops + fwd_bwd_ops + cooldown_ops
  2251. # warmup_ops + fwd_bwd_ops * 2 + cooldown_ops == microbatch_ops * 2
  2252. logger.debug(
  2253. "rank %s, warmup_ops %s, 1f1b %s, cooldown_ops %s total_ops %s",
  2254. rank,
  2255. warmup_ops,
  2256. fwd_bwd_ops,
  2257. cooldown_ops,
  2258. total_ops,
  2259. )
  2260. # Calculates the stage index based on step and pp_group_size
  2261. def forward_stage_index(step):
  2262. # Get the local index from 0 to n_local_stages-1
  2263. local_index = (step // self.microbatches_per_round) % self.n_local_stages
  2264. return (local_index * self.pp_group_size) + rank
  2265. def backward_stage_index(step):
  2266. local_index = (
  2267. self.n_local_stages
  2268. - 1
  2269. - ((step - warmup_ops) // self.microbatches_per_round)
  2270. % self.n_local_stages
  2271. )
  2272. return (local_index * self.pp_group_size) + rank
  2273. return _get_1f1b_rank_ops(
  2274. self.n_local_stages,
  2275. self.pp_group_size,
  2276. warmup_ops,
  2277. fwd_bwd_ops,
  2278. cooldown_ops,
  2279. rank,
  2280. forward_stage_index,
  2281. backward_stage_index,
  2282. )
  2283. class ScheduleInterleavedZeroBubble(_PipelineScheduleRuntime):
  2284. """
  2285. The Interleaved Zero Bubble schedule.
  2286. See https://arxiv.org/pdf/2401.10241 for details.
  2287. Will perform one forward and one backward on inputs for the microbatches in steady
  2288. state and supports multiple stages per rank. Uses the backward for weights to fill in
  2289. the pipeline bubble.
  2290. In particular this is implementing the ZB1P schedule in the paper.
  2291. """
  2292. def __init__(
  2293. self,
  2294. stages: list[_PipelineStageBase],
  2295. n_microbatches: int,
  2296. loss_fn: Callable | None = None,
  2297. args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
  2298. kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
  2299. output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
  2300. scale_grads: bool = True,
  2301. backward_requires_autograd: bool = True,
  2302. ):
  2303. # TODO: we dont support input/weight backward split with torch.compile
  2304. _check_torch_compile_compatibility(stages, self.__class__.__name__)
  2305. self.pp_group_size = stages[0].group_size
  2306. super().__init__(
  2307. stages=stages,
  2308. n_microbatches=n_microbatches,
  2309. loss_fn=loss_fn,
  2310. args_chunk_spec=args_chunk_spec,
  2311. kwargs_chunk_spec=kwargs_chunk_spec,
  2312. output_merge_spec=output_merge_spec,
  2313. scale_grads=scale_grads,
  2314. backward_requires_autograd=backward_requires_autograd,
  2315. )
  2316. self.n_local_stages = len(stages)
  2317. self.rank = stages[0].group_rank
  2318. self.number_of_rounds = max(1, n_microbatches // self.pp_group_size)
  2319. self.microbatches_per_round = n_microbatches // self.number_of_rounds
  2320. if n_microbatches % self.number_of_rounds != 0:
  2321. raise ValueError(
  2322. "Zero bubble requires the number of microbatches to be a "
  2323. f"multiple of the number of rounds ({self.number_of_rounds}), "
  2324. f"but got {n_microbatches}."
  2325. )
  2326. # 1. Create the pipeline_order (all ranks do this calculation)
  2327. # This will be used to keep track of the current state of the entire pipeline
  2328. # pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
  2329. self.pipeline_order: dict[int, list[_Action | None]] = {}
  2330. for rank in range(self.pp_group_size):
  2331. rank_ops = self._calculate_single_rank_operations(rank)
  2332. self.pipeline_order[rank] = rank_ops
  2333. # This function add bubbles to the generated schedule based on dependencies of actions
  2334. # Note that the ZB1P schedule will not require bubbles to be manually added and it is
  2335. # only useful when n_microbatches <= microbatches_per_round
  2336. self.pipeline_order = self._add_bubbles_to_actions(
  2337. self.n_local_stages * self.pp_group_size,
  2338. )
  2339. # Initialize the pipeline order with communication necessary to run with _PipelineScheduleRuntime
  2340. self._prepare_schedule_with_comms(self.pipeline_order)
  2341. def _calculate_single_rank_operations(self, rank) -> list[_Action | None]:
  2342. def get_rank_warmup_ops(rank):
  2343. # Warms up operations for last stage
  2344. warmups_ops_last_stage = (
  2345. self.n_local_stages - 1
  2346. ) * self.microbatches_per_round
  2347. # Increment warmup operations by 2 for each hop away from the last stage
  2348. multiply_factor = 1
  2349. warmup_ops = warmups_ops_last_stage + multiply_factor * (
  2350. (self.pp_group_size - 1) - rank
  2351. )
  2352. # We cannot have more warmup operations than there are number of microbatches, so cap it there
  2353. return min(warmup_ops, self._n_microbatches * self.n_local_stages)
  2354. warmup_ops = get_rank_warmup_ops(rank)
  2355. microbatch_ops = self.n_local_stages * self._n_microbatches
  2356. # fwd_bwd_ops should encompass the remaining forwards
  2357. fwd_bwd_ops = microbatch_ops - warmup_ops
  2358. # cooldown_ops should encompass the remaining backwards
  2359. cooldown_ops = microbatch_ops - fwd_bwd_ops
  2360. # total ops encompass both forward and backward ops
  2361. total_ops = warmup_ops + fwd_bwd_ops + cooldown_ops
  2362. # warmup_ops + fwd_bwd_ops * 2 + cooldown_ops == microbatch_ops * 2
  2363. logger.debug(
  2364. "rank %s, warmup_ops %s, 1f1b %s, cooldown_ops %s total_ops %s",
  2365. rank,
  2366. warmup_ops,
  2367. fwd_bwd_ops,
  2368. cooldown_ops,
  2369. total_ops,
  2370. )
  2371. # Calculates the stage index based on step and pp_group_size
  2372. def forward_stage_index(step):
  2373. # Get the local index from 0 to n_local_stages-1
  2374. local_index = (step // self.microbatches_per_round) % self.n_local_stages
  2375. return (local_index * self.pp_group_size) + rank
  2376. def backward_stage_index(step):
  2377. local_index = (
  2378. self.n_local_stages
  2379. - 1
  2380. - ((step - warmup_ops) // self.microbatches_per_round)
  2381. % self.n_local_stages
  2382. )
  2383. return (local_index * self.pp_group_size) + rank
  2384. num_1f1b_microbatches = rank
  2385. return _get_1f1b_rank_ops(
  2386. self.n_local_stages,
  2387. self.pp_group_size,
  2388. warmup_ops,
  2389. fwd_bwd_ops,
  2390. cooldown_ops,
  2391. rank,
  2392. forward_stage_index,
  2393. backward_stage_index,
  2394. num_1f1b_microbatches,
  2395. enable_zero_bubble=True,
  2396. )
  2397. def _add_bubbles_to_actions(self, num_stages_global):
  2398. actions = self.pipeline_order
  2399. def need_bubble(stage, op, microbatch, num_stages_global, seen_ops):
  2400. if op == _ComputationType.FORWARD:
  2401. if stage != 0 and (stage - 1, op, microbatch) not in seen_ops:
  2402. return True
  2403. elif op == _ComputationType.FULL_BACKWARD:
  2404. if stage == num_stages_global - 1:
  2405. return (stage, _ComputationType.FORWARD, microbatch) not in seen_ops
  2406. return (stage + 1, op, microbatch) not in seen_ops
  2407. return False
  2408. seen_ops: set[tuple[int, _ComputationType, int]] = set()
  2409. result: dict[int, list[_Action | None]] = {}
  2410. next_pointer: dict[int, int] = {}
  2411. bubbles_added: dict[int, int] = {}
  2412. total_bubbles_added = 0
  2413. for rank in range(self.pp_group_size):
  2414. result[rank] = []
  2415. next_pointer[rank] = 0
  2416. bubbles_added[rank] = 0
  2417. while True:
  2418. should_stop = True
  2419. temp_seen_ops: set[tuple[int, _ComputationType, int]] = set()
  2420. for rank in range(self.pp_group_size):
  2421. timestamp = next_pointer[rank]
  2422. if timestamp >= len(actions[rank]):
  2423. continue
  2424. should_stop = False
  2425. if actions[rank][timestamp] is not None:
  2426. temp_action = actions[rank][timestamp]
  2427. assert temp_action is not None
  2428. stage_index, op, microbatch, _ = temp_action
  2429. if not need_bubble(
  2430. stage_index, op, microbatch, num_stages_global, seen_ops
  2431. ):
  2432. result[rank].append(actions[rank][timestamp])
  2433. if microbatch is not None:
  2434. temp_seen_ops.add((stage_index, op, microbatch))
  2435. next_pointer[rank] += 1
  2436. else:
  2437. result[rank].append(None)
  2438. bubbles_added[rank] += 1
  2439. else:
  2440. next_pointer[rank] += 1
  2441. result[rank].append(None)
  2442. seen_ops.update(temp_seen_ops)
  2443. if should_stop:
  2444. break
  2445. if total_bubbles_added > 0:
  2446. logger.warning(
  2447. "Non zero bubbles added: total_bubbles_added=%s bubbles_added=%s",
  2448. total_bubbles_added,
  2449. bubbles_added,
  2450. )
  2451. return result
  2452. class ScheduleZBVZeroBubble(_PipelineScheduleRuntime):
  2453. """
  2454. The Zero Bubble schedule (ZBV variant).
  2455. See https://arxiv.org/pdf/2401.10241 Section 6 for details.
  2456. This schedules requires exactly two stages per rank.
  2457. This schedule will perform one forward and one backward on inputs for the microbatches in steady
  2458. state and supports multiple stages per rank. Uses backward with respect to weights to fill in
  2459. the pipeline bubble.
  2460. This ZB-V schedule would have the "zero bubble" property only if time forward == time backward input == time backward weights.
  2461. In practice, this is not likely true for real models so alternatively
  2462. a greedy scheduler could be implemented for unequal/unbalanced time.
  2463. """
  2464. def __init__(
  2465. self,
  2466. stages: list[_PipelineStageBase],
  2467. n_microbatches: int,
  2468. loss_fn: Callable | None = None,
  2469. args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
  2470. kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
  2471. output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
  2472. scale_grads: bool = True,
  2473. backward_requires_autograd: bool = True,
  2474. ):
  2475. # TODO: we dont support input/weight backward split with torch.compile
  2476. _check_torch_compile_compatibility(stages, self.__class__.__name__)
  2477. self.pp_group_size = stages[0].group_size
  2478. super().__init__(
  2479. stages=stages,
  2480. n_microbatches=n_microbatches,
  2481. loss_fn=loss_fn,
  2482. args_chunk_spec=args_chunk_spec,
  2483. kwargs_chunk_spec=kwargs_chunk_spec,
  2484. output_merge_spec=output_merge_spec,
  2485. scale_grads=scale_grads,
  2486. backward_requires_autograd=backward_requires_autograd,
  2487. )
  2488. self.stage_index_to_group_rank = generate_stage_to_rank_mapping(
  2489. self.pp_group_size, self._num_stages, style="v"
  2490. )
  2491. for stage in self._stages:
  2492. stage.stage_index_to_group_rank = self.stage_index_to_group_rank
  2493. self.n_local_stages = len(stages)
  2494. if self.n_local_stages != 2:
  2495. raise ValueError(
  2496. "ZBV requires exactly 2 stages per rank, but got "
  2497. f"{self.n_local_stages}."
  2498. )
  2499. self.rank = stages[0].group_rank
  2500. self.num_stages = stages[0].num_stages
  2501. # 1. Create the pipeline_order (all ranks do this calculation)
  2502. # This will be used to keep track of the current state of the entire pipeline
  2503. # pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
  2504. self.pipeline_order: dict[int, list[_Action | None]] = {}
  2505. for rank in range(self.pp_group_size):
  2506. rank_ops = self._calculate_single_rank_operations(rank)
  2507. self.pipeline_order[rank] = rank_ops
  2508. # Initialize the pipeline order with communication necessary to run with _PipelineScheduleRuntime
  2509. self._prepare_schedule_with_comms(self.pipeline_order)
  2510. def _calculate_single_rank_operations(self, rank) -> list[_Action | None]:
  2511. # max(2 * self.pp_group_size - 1, ...) ensure the number of microbatches is at least
  2512. # as large of the number of microbatches needed to fully utilize the pipeline
  2513. n_micro = max(2 * self.pp_group_size - 1, self._n_microbatches)
  2514. rank_ops: list[_Action | None] = [None for _ in range(rank)]
  2515. # Forward and backward action counts for stage chunk 0 and chunk 1
  2516. f0_cnt, f1_cnt, b0_cnt, b1_cnt = 0, 0, 0, 0
  2517. # warm-up phase
  2518. warmup_n1 = 2 * (self.pp_group_size - rank) - 1
  2519. stage_id_chunk0 = rank
  2520. stage_id_chunk1 = self.num_stages - 1 - rank
  2521. for _ in range(warmup_n1):
  2522. rank_ops.append(
  2523. _Action(stage_id_chunk0, computation_type=F, microbatch_index=f0_cnt)
  2524. )
  2525. f0_cnt += 1
  2526. warmup_n2 = rank
  2527. for _ in range(warmup_n2):
  2528. rank_ops.append(
  2529. _Action(stage_id_chunk1, computation_type=F, microbatch_index=f1_cnt)
  2530. )
  2531. f1_cnt += 1
  2532. rank_ops.append(
  2533. _Action(stage_id_chunk0, computation_type=F, microbatch_index=f0_cnt)
  2534. )
  2535. f0_cnt += 1
  2536. warmup_n3 = self.pp_group_size - rank
  2537. for _ in range(warmup_n3):
  2538. rank_ops.append(
  2539. _Action(stage_id_chunk1, computation_type=F, microbatch_index=f1_cnt)
  2540. )
  2541. f1_cnt += 1
  2542. rank_ops.append(
  2543. _Action(stage_id_chunk1, computation_type=I, microbatch_index=b1_cnt)
  2544. )
  2545. rank_ops.append(
  2546. _Action(stage_id_chunk1, computation_type=W, microbatch_index=b1_cnt)
  2547. )
  2548. b1_cnt += 1
  2549. # stable phase
  2550. while f1_cnt < f0_cnt or f0_cnt < n_micro:
  2551. if f0_cnt < n_micro:
  2552. rank_ops.append(
  2553. _Action(
  2554. stage_id_chunk0, computation_type=F, microbatch_index=f0_cnt
  2555. )
  2556. )
  2557. f0_cnt += 1
  2558. rank_ops.append(
  2559. _Action(stage_id_chunk0, computation_type=I, microbatch_index=b0_cnt)
  2560. )
  2561. rank_ops.append(
  2562. _Action(stage_id_chunk0, computation_type=W, microbatch_index=b0_cnt)
  2563. )
  2564. b0_cnt += 1
  2565. rank_ops.append(
  2566. _Action(stage_id_chunk1, computation_type=F, microbatch_index=f1_cnt)
  2567. )
  2568. f1_cnt += 1
  2569. rank_ops.append(
  2570. _Action(stage_id_chunk1, computation_type=I, microbatch_index=b1_cnt)
  2571. )
  2572. rank_ops.append(
  2573. _Action(stage_id_chunk1, computation_type=W, microbatch_index=b1_cnt)
  2574. )
  2575. b1_cnt += 1
  2576. # cool-down phase
  2577. w0_cnt, w1_cnt = b0_cnt, b1_cnt
  2578. cooldown_n1 = rank
  2579. for _ in range(cooldown_n1):
  2580. rank_ops.append(
  2581. _Action(stage_id_chunk0, computation_type=I, microbatch_index=b0_cnt)
  2582. )
  2583. b0_cnt += 1
  2584. rank_ops.append(
  2585. _Action(stage_id_chunk1, computation_type=I, microbatch_index=b1_cnt)
  2586. )
  2587. b1_cnt += 1
  2588. cooldown_n2 = self.pp_group_size - rank
  2589. for _ in range(cooldown_n2):
  2590. rank_ops.append(
  2591. _Action(stage_id_chunk0, computation_type=I, microbatch_index=b0_cnt)
  2592. )
  2593. b0_cnt += 1
  2594. rank_ops.append(
  2595. _Action(stage_id_chunk0, computation_type=W, microbatch_index=w0_cnt)
  2596. )
  2597. w0_cnt += 1
  2598. while w1_cnt < b1_cnt:
  2599. rank_ops.append(
  2600. _Action(stage_id_chunk1, computation_type=W, microbatch_index=w1_cnt)
  2601. )
  2602. w1_cnt += 1
  2603. while w0_cnt < b0_cnt:
  2604. rank_ops.append(
  2605. _Action(stage_id_chunk0, computation_type=W, microbatch_index=w0_cnt)
  2606. )
  2607. w0_cnt += 1
  2608. assert w0_cnt == b0_cnt and b0_cnt == f0_cnt
  2609. assert w1_cnt == b1_cnt and b1_cnt == f1_cnt
  2610. # We use max() in the n_micro computation above, so we may need to
  2611. # remove redundant microbatches
  2612. rank_ops = [
  2613. (
  2614. action
  2615. if action is not None
  2616. and action.microbatch_index is not None
  2617. and action.microbatch_index < self._n_microbatches
  2618. else None
  2619. )
  2620. for action in rank_ops
  2621. ]
  2622. return rank_ops
  2623. class ScheduleDualPipeV(_PipelineScheduleRuntime):
  2624. """
  2625. The DualPipeV schedule. A more efficient schedule variant based on the
  2626. DualPipe schedule introduced by DeepSeek in https://arxiv.org/pdf/2412.19437
  2627. Based on the open sourced code from https://github.com/deepseek-ai/DualPipe
  2628. """
  2629. def __init__(
  2630. self,
  2631. stages: list[_PipelineStageBase],
  2632. n_microbatches: int,
  2633. loss_fn: Callable | None = None,
  2634. args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
  2635. kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
  2636. output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
  2637. scale_grads: bool = True,
  2638. backward_requires_autograd: bool = True,
  2639. ):
  2640. # TODO: we dont support input/weight backward split with torch.compile
  2641. _check_torch_compile_compatibility(stages, self.__class__.__name__)
  2642. self.pp_group_size = stages[0].group_size
  2643. super().__init__(
  2644. stages=stages,
  2645. n_microbatches=n_microbatches,
  2646. loss_fn=loss_fn,
  2647. args_chunk_spec=args_chunk_spec,
  2648. kwargs_chunk_spec=kwargs_chunk_spec,
  2649. output_merge_spec=output_merge_spec,
  2650. scale_grads=scale_grads,
  2651. backward_requires_autograd=backward_requires_autograd,
  2652. )
  2653. self.stage_index_to_group_rank = generate_stage_to_rank_mapping(
  2654. self.pp_group_size, self._num_stages, style="v"
  2655. )
  2656. for stage in self._stages:
  2657. stage.stage_index_to_group_rank = self.stage_index_to_group_rank
  2658. self.n_local_stages = len(stages)
  2659. if self.n_local_stages != 2:
  2660. raise ValueError(
  2661. "ZBV requires exactly 2 stages per rank, but got "
  2662. f"{self.n_local_stages}."
  2663. )
  2664. if n_microbatches < self._num_stages:
  2665. raise ValueError(
  2666. "DualPipeV requires at least as many microbatches as stages, but got "
  2667. f"{n_microbatches} microbatches and {self._num_stages} stages."
  2668. )
  2669. self.rank = stages[0].group_rank
  2670. self.num_stages = stages[0].num_stages
  2671. # 1. Create the pipeline_order (all ranks do this calculation)
  2672. # This will be used to keep track of the current state of the entire pipeline
  2673. # pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
  2674. self.pipeline_order: dict[int, list[_Action | None]] = {}
  2675. for rank in range(self.pp_group_size):
  2676. rank_ops = self._calculate_single_rank_operations(rank)
  2677. self.pipeline_order[rank] = rank_ops
  2678. # Initialize the pipeline order with communication necessary to run with _PipelineScheduleRuntime
  2679. self._prepare_schedule_with_comms(self.pipeline_order)
  2680. def _calculate_single_rank_operations(self, rank) -> list[_Action | None]:
  2681. actions: list[_Action | None] = []
  2682. counters: dict[
  2683. tuple[int, _ComputationType], int
  2684. ] = {} # (stage_index, computation_type) -> mb_index
  2685. weight_queue = [] # Queue of (stage_index, mb_index) for pending weight actions
  2686. num_ranks = self.pp_group_size
  2687. num_chunks = self._n_microbatches
  2688. rank_to_stages = generate_rank_to_stage_mapping(
  2689. num_ranks, num_ranks * 2, style="v"
  2690. )
  2691. stage0_index, stage1_index = rank_to_stages[rank]
  2692. def increment_backward_counts(stage_index: int):
  2693. """Helper method to increment BACKWARD_INPUT and BACKWARD_WEIGHT counters when FULL_BACKWARD is used."""
  2694. input_key = (stage_index, BACKWARD_INPUT)
  2695. weight_key = (stage_index, BACKWARD_WEIGHT)
  2696. counters[input_key] = counters.get(input_key, 0) + 1
  2697. counters[weight_key] = counters.get(weight_key, 0) + 1
  2698. def add_overlap_f_b(
  2699. actions: list,
  2700. forward_stage: int,
  2701. backward_stage: int,
  2702. ):
  2703. """Helper method to add an overlapped forward+backward action which tracks microbatch index."""
  2704. # Create new overlapped forward+backward action with sub_actions
  2705. forward_key = (forward_stage, FORWARD)
  2706. backward_key = (backward_stage, BACKWARD_INPUT)
  2707. forward_mb = counters.get(forward_key, 0)
  2708. backward_mb = counters.get(backward_key, 0)
  2709. sub_actions = (
  2710. _Action(forward_stage, FORWARD, forward_mb),
  2711. _Action(backward_stage, FULL_BACKWARD, backward_mb),
  2712. )
  2713. actions.append(_Action(-1, OVERLAP_F_B, None, sub_actions))
  2714. # Update counters for sub_actions
  2715. counters[forward_key] = forward_mb + 1
  2716. increment_backward_counts(backward_stage)
  2717. def add_action(
  2718. actions: list,
  2719. stage_index: int,
  2720. computation_type: _ComputationType,
  2721. ):
  2722. # Regular single action, for FULL_BACKWARD we only use the BACKWARD_INPUT counter
  2723. key = (
  2724. (stage_index, computation_type)
  2725. if computation_type != FULL_BACKWARD
  2726. else (stage_index, BACKWARD_INPUT)
  2727. )
  2728. mb_index = counters.get(key, 0)
  2729. actions.append(_Action(stage_index, computation_type, mb_index))
  2730. # If FULL_BACKWARD is used, just increment the separate BACKWARD_INPUT and BACKWARD_WEIGHT counters
  2731. if computation_type == FULL_BACKWARD:
  2732. increment_backward_counts(stage_index)
  2733. else:
  2734. # If BACKWARD_INPUT is updated, add corresponding weight action to queue
  2735. if computation_type == BACKWARD_INPUT:
  2736. # Add weight action to queue for later processing
  2737. weight_queue.append((stage_index, mb_index))
  2738. counters[key] = mb_index + 1
  2739. def add_weight_action_if_pending(actions: list):
  2740. """Helper method to add a weight action from the queue."""
  2741. if not weight_queue:
  2742. return # No pending weight actions, skip
  2743. # Pop the oldest weight action from the queue
  2744. actual_stage_index, weight_mb_index = weight_queue.pop(0)
  2745. actions.append(
  2746. _Action(
  2747. actual_stage_index,
  2748. BACKWARD_WEIGHT,
  2749. weight_mb_index,
  2750. )
  2751. )
  2752. # Update the counter for the actual stage that was processed
  2753. weight_key = (actual_stage_index, BACKWARD_WEIGHT)
  2754. counters[weight_key] = counters.get(weight_key, 0) + 1
  2755. # Step 1: F0
  2756. step_1 = (num_ranks - rank - 1) * 2
  2757. for _ in range(step_1):
  2758. add_action(actions, stage0_index, FORWARD)
  2759. # Step 2: F0F1
  2760. step_2 = rank + 1
  2761. for _ in range(step_2):
  2762. add_action(actions, stage0_index, FORWARD)
  2763. add_action(actions, stage1_index, FORWARD)
  2764. # Step 3: I1W1F1 (Use zero bubble)
  2765. step_3 = num_ranks - rank - 1
  2766. for _ in range(step_3):
  2767. add_action(actions, stage1_index, BACKWARD_INPUT)
  2768. add_weight_action_if_pending(actions)
  2769. add_action(actions, stage1_index, FORWARD)
  2770. # Step 4 (Main step): F0B1-F1B0 (combined, overlapped forward+backward)
  2771. step_4 = num_chunks - num_ranks * 2 + rank + 1
  2772. for i in range(step_4):
  2773. if i == 0 and rank == num_ranks - 1:
  2774. # NOTE: We don't overlap these two chunks to further reduce bubble size.
  2775. add_action(actions, stage0_index, FORWARD)
  2776. add_action(actions, stage1_index, FULL_BACKWARD)
  2777. else:
  2778. add_overlap_f_b(
  2779. actions,
  2780. forward_stage=stage0_index,
  2781. backward_stage=stage1_index,
  2782. )
  2783. add_overlap_f_b(
  2784. actions,
  2785. forward_stage=stage1_index,
  2786. backward_stage=stage0_index,
  2787. )
  2788. # Step 5: B1-F1B0
  2789. step_5 = num_ranks - rank - 1
  2790. for _ in range(step_5):
  2791. add_action(actions, stage1_index, FULL_BACKWARD)
  2792. add_overlap_f_b(
  2793. actions,
  2794. forward_stage=stage1_index,
  2795. backward_stage=stage0_index,
  2796. )
  2797. # Step 6: B1B0 (The second half of the chunks use zero bubble)
  2798. step_6 = rank + 1
  2799. enable_zb = False
  2800. for i in range(step_6):
  2801. if i == step_6 // 2 and rank % 2 == 1:
  2802. enable_zb = True
  2803. comp_type = BACKWARD_INPUT if enable_zb else FULL_BACKWARD
  2804. add_action(actions, stage1_index, comp_type)
  2805. if i == step_6 // 2 and rank % 2 == 0:
  2806. enable_zb = True
  2807. comp_type = BACKWARD_INPUT if enable_zb else FULL_BACKWARD
  2808. add_action(actions, stage0_index, comp_type)
  2809. # Step 7: W0B0
  2810. step_7 = num_ranks - rank - 1
  2811. for _ in range(step_7):
  2812. add_weight_action_if_pending(actions)
  2813. comp_type = BACKWARD_INPUT if enable_zb else FULL_BACKWARD
  2814. add_action(actions, stage0_index, comp_type)
  2815. # Step 8: W0
  2816. step_8 = rank + 1
  2817. for _ in range(step_8):
  2818. add_weight_action_if_pending(actions)
  2819. return actions
  2820. def get_schedule_class(schedule_name: str):
  2821. """
  2822. Maps a schedule name (case insensitive) to its corresponding class object.
  2823. Args:
  2824. schedule_name (str): The name of the schedule.
  2825. """
  2826. schedule_map = {
  2827. "1F1B": Schedule1F1B,
  2828. "Interleaved1F1B": ScheduleInterleaved1F1B,
  2829. "GPipe": ScheduleGPipe,
  2830. "LoopedBFS": ScheduleLoopedBFS,
  2831. "InterleavedZeroBubble": ScheduleInterleavedZeroBubble,
  2832. "PipelineScheduleSingle": PipelineScheduleSingle,
  2833. "PipelineScheduleMulti": PipelineScheduleMulti,
  2834. "ZBVZeroBubble": ScheduleZBVZeroBubble,
  2835. "DualPipeV": ScheduleDualPipeV,
  2836. }
  2837. lowercase_keys = {k.lower(): k for k in schedule_map}
  2838. lowercase_schedule_name = schedule_name.lower()
  2839. if lowercase_schedule_name not in lowercase_keys:
  2840. raise ValueError(
  2841. f"Unknown schedule name '{schedule_name}'. The valid options are {list(schedule_map.keys())}"
  2842. )
  2843. return schedule_map[lowercase_keys[lowercase_schedule_name]]
  2844. def _simulate_comms_compute(
  2845. pipeline_order, stage_to_rank: Callable[[int], int], num_stages: int
  2846. ):
  2847. """This function dry-run simulates the actions in the schedule from the perspective of all ranks, and flags
  2848. any deadlocks caused by missing or misordered communications. It also simulates any bubbles in time where a rank
  2849. can not execute any action due to waiting for unmet dependencies. The total number of simulator steps can be used
  2850. as a metric for unit tests involving IR optimization passes as reordering and merging of IR can reduce the number
  2851. of simulated steps.
  2852. The simulation is not high-fidelity and does not model overlapping of compute and communication, or cuda streams.
  2853. Future work may be to enhance this and model the compute time, comms overlap, and even memory.
  2854. """
  2855. pipeline_order = {
  2856. rank: [a for a in pipeline_order[rank] if a is not None]
  2857. for rank in sorted(pipeline_order)
  2858. }
  2859. _schedule: dict[int, list[_Action | None]] = {
  2860. rank: [] for rank in sorted(pipeline_order)
  2861. }
  2862. _prev_ops_rank: dict[int, set[_Action]] = {rank: set() for rank in _schedule}
  2863. def add_to_schedule(rank: int, action: _Action | None):
  2864. _schedule[rank].append(action)
  2865. if action is not None:
  2866. _prev_ops_rank[rank].add(action)
  2867. def _ready_to_schedule(action: _Action | None) -> bool:
  2868. if action is None:
  2869. return True
  2870. stage_idx = action.stage_index
  2871. prev_ops = _prev_ops_rank[stage_to_rank(stage_idx)]
  2872. if action.computation_type == F:
  2873. if action.stage_index == 0:
  2874. return True
  2875. elif (
  2876. _Action(action.stage_index, RECV_F, action.microbatch_index) in prev_ops
  2877. ):
  2878. return True
  2879. elif (
  2880. _Action(action.stage_index - 1, F, action.microbatch_index) in prev_ops
  2881. ):
  2882. return True
  2883. return False
  2884. elif action.computation_type in (BACKWARD_INPUT, FULL_BACKWARD):
  2885. if action.stage_index == num_stages - 1:
  2886. return True
  2887. if _Action(action.stage_index, RECV_B, action.microbatch_index) in prev_ops:
  2888. return True
  2889. if (
  2890. _Action(action.stage_index + 1, BACKWARD_INPUT, action.microbatch_index)
  2891. in prev_ops
  2892. ):
  2893. return True
  2894. if (
  2895. _Action(action.stage_index + 1, FULL_BACKWARD, action.microbatch_index)
  2896. in prev_ops
  2897. ):
  2898. return True
  2899. return False
  2900. elif action.computation_type == BACKWARD_WEIGHT:
  2901. return True
  2902. elif action.computation_type == SEND_F:
  2903. expected_f = _Action(action.stage_index, F, action.microbatch_index)
  2904. return expected_f in prev_ops
  2905. elif action.computation_type == RECV_F:
  2906. peer_stage_idx = stage_idx - 1
  2907. expected_send = _Action(peer_stage_idx, SEND_F, action.microbatch_index)
  2908. return expected_send in _prev_ops_rank[stage_to_rank(peer_stage_idx)]
  2909. elif action.computation_type == SEND_B:
  2910. expected_b = _Action(
  2911. action.stage_index, BACKWARD_INPUT, action.microbatch_index
  2912. )
  2913. expected_bw = _Action(
  2914. action.stage_index, FULL_BACKWARD, action.microbatch_index
  2915. )
  2916. return expected_b in prev_ops or expected_bw in prev_ops
  2917. elif action.computation_type == RECV_B:
  2918. peer_stage_idx = stage_idx + 1
  2919. expected_send = _Action(peer_stage_idx, SEND_B, action.microbatch_index)
  2920. return expected_send in _prev_ops_rank[stage_to_rank(peer_stage_idx)]
  2921. else:
  2922. raise ValueError(f"Unsupported action type {action}")
  2923. while pipeline_order:
  2924. progress = False
  2925. for rank in sorted(pipeline_order):
  2926. if len(pipeline_order[rank]) == 0:
  2927. continue
  2928. action = pipeline_order[rank][0]
  2929. if _ready_to_schedule(action):
  2930. if action is not None:
  2931. add_to_schedule(rank, action)
  2932. pipeline_order[rank].pop(0)
  2933. progress = True
  2934. else:
  2935. add_to_schedule(rank, None)
  2936. for i in sorted(pipeline_order, reverse=True):
  2937. if len(pipeline_order[i]) == 0:
  2938. del pipeline_order[i]
  2939. # hacky, but do a second pass to replace any 'none' at this timestep with a real action, if it got unblocked
  2940. # by one of the later ranks
  2941. for rank in sorted(pipeline_order):
  2942. if len(pipeline_order[rank]) == 0:
  2943. continue
  2944. if _schedule[rank][-1] is not None:
  2945. continue
  2946. action = pipeline_order[rank][0]
  2947. if _ready_to_schedule(action):
  2948. if action is not None:
  2949. _schedule[rank][-1] = action
  2950. _prev_ops_rank[rank].add(action)
  2951. pipeline_order[rank].pop(0)
  2952. for i in sorted(pipeline_order, reverse=True):
  2953. if len(pipeline_order[i]) == 0:
  2954. del pipeline_order[i]
  2955. if not progress:
  2956. print("WIP comms schedule:\n", _format_pipeline_order(_schedule))
  2957. for rank in pipeline_order:
  2958. print(f"{rank=} next action= {pipeline_order[rank][0]}")
  2959. raise ValueError("Schedule is not progressing")
  2960. return _schedule
  2961. def _dump_chrometrace(schedule, filename):
  2962. """
  2963. This function dumps a schedule IR into a chrometrace format so it can be visualized.
  2964. It is currently very basic and only serves as a graphical alternative to dumping the schedule IR as text.
  2965. As future work we may extend this to include more accurate heuristics for durations, or let users input durations,
  2966. add 'flow events' to let the UI show the connection between sends and recvs, and model cuda streams for comm/compute
  2967. as separate streams on the chrometrace view.
  2968. """
  2969. events = []
  2970. for rank in sorted(schedule):
  2971. for timestep, action in enumerate(schedule[rank]):
  2972. if action is None:
  2973. continue
  2974. events.append(
  2975. {
  2976. "name": str(action),
  2977. "cat": (
  2978. "computation"
  2979. if action.computation_type in (F, B, W)
  2980. else "communication"
  2981. ),
  2982. "ph": "X",
  2983. "pid": rank,
  2984. "tid": rank,
  2985. "ts": timestep,
  2986. "dur": 1,
  2987. }
  2988. )
  2989. import json
  2990. with open(filename, "w") as f:
  2991. json.dump({"traceEvents": events}, f)
  2992. def _check_torch_compile_compatibility(
  2993. stages: list[_PipelineStageBase], schedule_name: str
  2994. ):
  2995. """
  2996. Check if the schedule is compatible with torch.compile.
  2997. Args:
  2998. stages: List of pipeline stages to check
  2999. schedule_name: Name of the schedule for error message
  3000. Raises:
  3001. RuntimeError: If any stage uses torch.compile
  3002. """
  3003. for stage in stages:
  3004. if not isinstance(stage.submod, torch.nn.Module):
  3005. continue
  3006. for module in stage.submod.modules():
  3007. if isinstance(module, OptimizedModule):
  3008. raise RuntimeError(
  3009. f"The {schedule_name} schedule is not supported with "
  3010. "stage modules that have used torch.compile. "
  3011. f"Found OptimizedModule in {type(module).__name__}"
  3012. )