<?xml-model href='http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng' schematypens='http://relaxng.org/ns/structure/1.0'?><TEI xmlns="http://www.tei-c.org/ns/1.0">
	<teiHeader>
		<fileDesc>
			<titleStmt><title level='a'>Hindsight logging for model training</title></titleStmt>
			<publicationStmt>
				<publisher></publisher>
				<date>12/01/2020</date>
			</publicationStmt>
			<sourceDesc>
				<bibl> 
					<idno type="par_id">10219496</idno>
					<idno type="doi">10.14778/3436905.3436925</idno>
					<title level='j'>Proceedings of the VLDB Endowment</title>
<idno>2150-8097</idno>
<biblScope unit="volume">14</biblScope>
<biblScope unit="issue">4</biblScope>					

					<author>Rolando Garcia</author><author>Eric Liu</author><author>Vikram Sreekanti</author><author>Bobby Yan</author><author>Anusha Dandamudi</author><author>Joseph E. Gonzalez</author><author>Joseph M. Hellerstein</author><author>Koushik Sen</author>
				</bibl>
			</sourceDesc>
		</fileDesc>
		<profileDesc>
			<abstract><ab><![CDATA[In modern Machine Learning, model training is an iterative, experimental process that can consume enormous computation resources and developer time. To aid in that process, experienced model developers log and visualize program variables during training runs. Exhaustive logging of all variables is infeasible, so developers are left to choose between slowing down training via extensive              conservative              logging, or letting training run fast via minimalist              optimistic              logging that may omit key information. As a compromise, optimistic logging can be accompanied by program checkpoints; this allows developers to add log statements post-hoc, and "replay" desired log statements from checkpoint---a process we refer to as              hindsight              logging. Unfortunately, hindsight logging raises tricky problems in data management and software engineering. Done poorly, hindsight logging can waste resources and generate technical debt embodied in multiple variants of training code. In this paper, we present methodologies for efficient and effective logging practices for model training, with a focus on techniques for hindsight logging. Our goal is for experienced model developers to learn and adopt these practices. To make this easier, we provide an open-source suite of tools for Fast Low-Overhead Recovery (flor) that embodies our design across three tasks: (i) efficient background logging in Python, (ii) adaptive periodic checkpointing, and (iii) an instrumentation library that codifies hindsight logging for efficient and automatic record-replay of model-training. Model developers can use each flor tool separately as they see fit, or they can use flor in hands-free mode, entrusting it to instrument their code end-to-end for efficient record-replay. Our solutions leverage techniques from physiological transaction logs and recovery in database systems. Evaluations on modern ML benchmarks demonstrate that flor can produce fast checkpointing with small user-specifiable overheads (e.g. 7%), and still provide hindsight log replay times orders of magnitude faster than restarting training from scratch.]]></ab></abstract>
		</profileDesc>
	</teiHeader>
	<text><body xmlns="http://www.tei-c.org/ns/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink">
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="1">INTRODUCTION</head><p>Due to the growing scale and complexity of sophisticated models <ref type="bibr">[14,</ref><ref type="bibr">44,</ref><ref type="bibr">56]</ref>, exploratory model development increasingly poses data management problems <ref type="bibr">[53]</ref>. At every step of exploration, model developers routinely track and visualize time series data to diagnose common training problems such as exploding/vanishing gradients <ref type="bibr">[20]</ref>, dead ReLUs <ref type="bibr">[33]</ref>, and reward hacking <ref type="bibr">[6]</ref>. Model developers use state-of-the-art loggers specialized to machine learning (e.g. TensorBoard <ref type="bibr">[17]</ref>, and WandB In our experience, all model developers log some training metrics by default. Whether their logging practice is characteristically conservative or optimistic depends on whether they log additional training data by default. Next, we will illustrate the relevant differences between conservative and optimistic logging, by introducing three archetypal characters: Mike for methodical conservative logging, Chuck for ad-hoc optimistic logging, and Judy for methodical optimistic logging.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="1.1">Conservative Logging</head><p>Conservative logging is eager and characterized by stable expectations about what data (and how much of it) will be necessary for analysis <ref type="bibr">[64]</ref>. It is especially well-suited to later stages of the machine learning lifecycle, where models are periodically trained emailing info@vldb.org. Copyright is held by the owner/author(s). Publication rights licensed to the VLDB Endowment. Proceedings of the VLDB Endowment, Vol. 14, No. 4 ISSN 2150-8097. doi:10.14778/3436905.3436925 for many hours on fresh data <ref type="bibr">[55]</ref>, and refinements of the model training pipeline are usually light and limited to hyper-parameter tuning <ref type="bibr">[16]</ref>.</p><p>1.1.1 Mike records everything (mnemonic for microphone). Mike is a model developer for a major tech company. His organization's policy is that model developers should log training metrics, tensor histograms, and some images and overlays by default. Although his logging practices can add substantial overhead to training (black bar in Figure <ref type="figure">1</ref>), his jobs usually run as offline batches, and his productivity is not blocked on the results of training. Moreover, when he receives an alert from the training or monitoring system, the execution data he needs for post-hoc analysis will be ready.</p><p>Although reducing logging overhead is not a high priority for Mike, he is not the only developer in his organization using highend GPU clusters. At scale, even minor improvements to training efficiency will translate into measurable benefits for the organization. Later in this paper, we will present a tool for low-overhead materialization in the background (Section 3.1). Our tool enables Mike to continue to log data at the same rate and with his logger of choice (e.g. tensorboardx), at a fraction of the original overhead (purple bar in Figure <ref type="figure">1</ref>).</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="1.2">Optimistic Logging</head><p>In contrast to conservative logging, optimistic logging is an agile and lazy practice especially well-suited to early and unstructured stages of exploratory model development. In optimistic logging, model developers log training metrics such as the loss and accuracy by default, and defer collection of additional data until analysis time, when they may restore it selectively. Execution data is restored by adding logging statements to training post-hoc, and replayingpossibly from checkpoint. We refer to this practice as hindsight logging. Optimistic logging consists of (i) logging some training metrics by default, and (ii) selectively restoring additional training data post-hoc with hindsight logging.</p><p>Model developers gain agility in exploration from optimistic logging in three ways:</p><p>&#8226; Deferred Overhead: Each training batch executes and produces results as quickly as possible. Exploration time is finite, and the more alternatives a model developer can explore, the better. and how much of it do not burden the developer during design and tuning. These considerations are postponed until analysis time.</p><p>In the fast path of the common case, model developers get all the relevant information from the training loss, and move on. In exceptional cases, however, training replay may be necessary for post-hoc data restoration.</p><p>1. When either Chuck or Judy need to restore training data posthoc-say, the tensor histograms for the gradients at a rate of 4&#215; per epoch-they will selectively add the necessary logging statements to their training code, and re-train. In many cases, Chuck and Judy will only want to restore data for a small fraction of training (e.g. 25% of the epochs), near the region where the loss exhibits an anomaly (e.g. near the middle of training). Because Judy checkpointed her training execution, she is able to resume training at an arbitrary epoch. Chuck, on the other hand, must retrain from the start. In the right pane of Figure <ref type="figure">1</ref>, we plot training plus replay times for Chuck (blue line) and Judy (green line).</p><p>In this paper, we will concretely define the methodology that enables Judy to achieve effective record-replay of model training (Section 2). Our goal is for experienced model developers to learn and adopt these best practices, for their numerous benefits. One surprising consequence of Judy's approach is that she can parallelize replay of model training with her periodic checkpoints (Section 2.2). The purple line in Figure <ref type="figure">1</ref> represents Judy's parallel replay.</p><p>Additionally, we evaluate (Section 4) and open-source <ref type="bibr">[15]</ref> our Fast Low-Overhead Recovery suite (abbreviated as flor) for hindsight logging-with the following set of tools:</p><p>&#8226; An optimized materialization library for low-overhead logging and checkpointing in Python (Section 3.1). &#8226; An adaptable periodic checkpointing mechanism to control record overhead, so it never exceeds a user-specifiable limit (Section 3.2).</p><p>&#8226; An instrumentation library that can transparently transform Python training code to conform with the methodical hindsight logging approach (Section 3.3). This protects model developers from incurring technical debt as a consequence of lapses in discipline, and enables novices to restore time series data as efficiently as experts. Model developers may use each flor tool separately as they see fit, or they may use flor in hands-free mode, entrusting it to instrument their code end-to-end for efficient record-replay.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2">METHODICAL HINDSIGHT LOGGING</head><p>In hindsight logging, model developers can choose what to log long after model training: at analysis time and with a question in mind. In essence, we want to query past execution state, without versioning that state in full. We draw inspiration from the rich body of work in databases dedicated to fast recovery <ref type="bibr">[39,</ref><ref type="bibr">62,</ref><ref type="bibr">67]</ref>. Although that work focuses mostly on transactions, the lessons and trade-offs transfer naturally to execution recovery for arbitrary programs. There are two means for recovering execution data: physically, by reading it from disk; and logically, by recomputing it. Both a purely physical approach and a purely logical approach are unattractive in our setting, due to prohibitive overhead on record and prohibitive latency on replay, respectively. Instead, hindsight logging-like transaction logging-embraces a hybrid "physiological" <ref type="bibr">[18]</ref> approach that takes partial checkpoints on the first pass (henceforth the record phase), and uses those checkpoints to speedup redo (henceforth the replay phase).</p><p>In this section, we give a high-level overview of the enabling methodology behind efficient hindsight logging:</p><p>(1) First and foremost, checkpoint periodically during training. At least once per epoch for partial replay, but much less frequently is sufficient for parallel replay. (2) Additionally, enclose long-running code inside a conditional statement to exploit memoization speedups. On record, the execution materializes the side-effects of each memoized block. On replay, model developers will run their code from the beginning without modification, and the execution will intelligently skip the recomputation of some If at any point through our forthcoming discussion the programming burden seems too high, the reader should note that we also provide a tool that codifies and automatically applies these methods for the benefit of the user: an instrumentation library that features a hands-free mode for convenience and robustness (Section 3.3).</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.1">Periodic Checkpointing &amp; Memoization</head><p>Many model developers already checkpoint training periodically. This is traditionally done for warm-starting training as well as for fault tolerance. In this section, we show how to exploit further benefits from periodic checkpointing, without incurring additional overheads.</p><p>In Figure <ref type="figure">2</ref>, we provide an example of how a model developer would materialize the model and optimizer state once per epoch (line 10). This state serves a dual purpose. First, it comprises the relevant side-effects of the preceding code block (lines 4-9), so it serves a memoization purpose (computation skipping). Second, it captures all of the state that is modified every epoch of training, so it comprises a valid and complete checkpoint. This dual purpose of selective state capture is a fortunate coincidence that arises naturally from the nested loops structure of model training.</p><p>We make use of the SkipBlock language construct <ref type="bibr">[11]</ref>, to denote block memoization. The first two requirements for efficient recordreplay are periodic checkpointing and block memoization. Both are achievable by the following functionality, which is encapsulated by the SkipBlock for ease of exposition: When the enclosed block is executed, SkipBlock materializes its side-effects (the arguments passed to the call in line 10, Figure <ref type="figure">2</ref>). It is possible to optimize the SkipBlock for low-overhead background materialization (Section 3.1), and adaptable periodic materialization (Section 3.2), but these optimizations do not alter the semantics of SkipBlock. &#8226; Side-Effect Restoration: Whenever the enclosed block is skipped, SkipBlock restores its side-effects from its corresponding checkpoint (line 10, Figure <ref type="figure">2</ref>). SkipBlock is able to efficiently locate an execution's corresponding checkpoint on disk, and apply its side-effects to the program state. A block may not be skipped on replay if the model developer adds a hindsight logging statement inside the block. Although Skip-Block memoizes the block's final state (that is visible to subsequent statements), it does not materialize intermediate state, such as the activations of the model (line 6 in Figure <ref type="figure">2</ref>). Consequently, if the model developer wishes to restore the model activations post-hoc, it will not be possible to skip the nested training loop. In such cases, parallel replay is the only option for reducing the latency of hindsight logging.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.2">Parallel Replay by Checkpoint Resume</head><p>As we saw in the previous subsection, our approach cannot avoid expensive recomputation when intermediate training state, such as the gradients or activations are logged post-hoc. In such cases, model developers will want to reduce replay latency by utilizing additional resources-specifically, more GPUs for parallelism. Although auto-parallelizing arbitrary sequential code remains an open challenge <ref type="bibr">[8]</ref>, the replay of checkpointed model training is a special case: training replay is embarrassingly parallel given periodic checkpoints.</p><p>As we multi-purposed periodic checkpointing in the previous section for memoization, so too we now multi-purpose checkpoint resume-a current staple in the training code of many model developers-for parallel replay. Parallel replay enables us to substantially cut hindsight logging latency, and due to the prevalence of checkpoint resume, this is possible without incurring a programming burden. To parallelize replay, a model developer simultaneously resumes training from various checkpoints:</p><p>(1) First, a model developer dispatches multiple training jobs (in parallel) (2) Then, each job loads the checkpoint (line 2 in Figure <ref type="figure">2</ref>) that corresponds to the epoch it is resuming from. For example, to resume training at epoch 25, the job loads the checkpoint stored at the end of epoch 24.</p><p>(3) Finally, each job independently works on its share of work (see the range in line 3 of Figure <ref type="figure">2</ref>).</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>2.2.1</head><p>Pseudoresuming from partial checkpoints. When model developers write code for periodic checkpointing themselves, they can ensure that the objects they capture constitute a complete checkpoint. However, when model developers entrust flor to instrument their code for automatic periodic checkpointing, flor will not be able to automatically determine whether the checkpoint is complete or partial with respect to training. As we will discuss in Section 3.3, flor can only estimate the side-effects of blocks of code enclosed by SkipBlocks: a restriction we use to render our static analysis tractable. flor will not estimate the side-effects of the program at arbitrary points, and it will not check whether the data materialized constitutes a complete (or partial) checkpoint with respect to training, since doing so statically (i.e. with low overhead) would be intractable in Python <ref type="bibr">[21,</ref><ref type="bibr">41,</ref><ref type="bibr">52]</ref>. Consequently, flor assumes checkpoints materialized automatically are partial with respect to training. By partial, we mean that there are objects modified every epoch that are not stored by the checkpoints (e.g. the lr_scheduler in Figure <ref type="figure">3</ref>). As a result, it is not possible to resume training from an arbitrary epoch merely by loading a partial checkpoint (i.e. a physical recovery approach). Instead, we start training from the beginning (line 2 in Figure <ref type="figure">3</ref>), and use the partial checkpoints to skip recomputation of memoized blocks during the initialization -or pseudoresume -phase (lines 3-4 in Figure <ref type="figure">3</ref>). This approach is characteristically physiological because it relies on a combination of recomputation and disk reads for recovery. Although pseudoresume is especially important for auto-parallelizing replay of model training, we share this method here because novice model developer may accidentally store partial checkpoints. This technique allows them to resume training efficiently all the same.</p><p>For illustration, suppose, that the model developer wants to resume training from epoch 25, using the script in Figure <ref type="figure">3</ref>. Pseudoresume phase for epochs in the range 0-24 (inclusive):</p><p>(1) SkipBlock skips the nested training loop (lines 3-4 in Fig-</p><p>ure <ref type="figure">3</ref>). (2) SkipBlock loads the side-effects of the nested training loop from disk (line 10 in Figure <ref type="figure">3</ref>). (3) All other statements execute normally.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>Execution phase from epoch 25 onward:</head><p>(1) SkipBlock enters (steps into) the nested training loop (lines 3-4 in Figure <ref type="figure">3</ref>). (2) All other statements execute normally.</p><p>In summary, memoization can be used to resume model training from an arbitrary epoch, even in the absence of complete checkpoints. As we will show in the evaluation, the overhead of pseudoresume is amortized in parallel replay, so that the difference between checkpoint resume and pseudoresume is imperceivable to the enduser. This result is important because it enables us to efficiently auto-parallelize the replay of model training, even without complete checkpoints.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3">TOOLING FOR HINDSIGHT LOGGING</head><p>We provide a suite of Fast Low-Overhead Recovery tools-flor for short-as aid to the developer. Model developers may use each tool separately as they see fit, or they may use flor in hands-free mode, entrusting it to instrument their code end-to-end for efficient record-replay. flor provides the following tools:</p><p>&#8226; An optimized materialization library for low-overhead logging and checkpointing (Section 3.1). &#8226; An adaptable periodic checkpointing mechanism to control record overhead, so it never exceeds a user-specifiable limit (Section 3.2). &#8226; An instrumentation library that can transparently transform training code to conform to the methodical hindsight logging approach (Section 3.3). This protects model developers from incurring technical debt as a consequence of lapses in discipline, and enables novices to restore time series data as efficiently as experts.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.1">Background Logging</head><p>flor provides a background materialization mechanism optimized for PyTorch, which is compatible with model developer's machine learning logging service of choice (for example, TensorBoard <ref type="bibr">[17]</ref>, MLFlow <ref type="bibr">[65]</ref>, and WandB [1]). Background logging is used natively by SkipBlocks for low-overhead periodic checkpointing (Section 2.1). It is also available separately as a library for end-users. Both logging and checkpointing can add measurable overhead to training because they require moving data from GPU memory to DRAM, serializing it into byte arrays, and then writing those arrays to disk. Of the latter two, serialization is typically much more expensive than I/O: by an average factor of 4.3&#215; according to our microbenchmarks <ref type="bibr">[30]</ref>. Consequently, after copying select data from GPU memory to DRAM (so it is protected from overwrites), we would like to take materialization (both serialization and I/O) off the main thread-which is dedicated to model training-and do it in the background.</p><p>Despite its maturity and widespread popularity, Python makes this very difficult. The Python interpreter has a notorious Global Interpreter Lock that prevents parallelism among Python threads. Unfortunately, the Python IPC schemes (e.g., the multiprocessing library) also require serialization by the sending process-returning us to our original problem. To avoid serialization we could use a solution like Apache Plasma, but it only avoids serialization for a subset of Python data types (notably dataframes and arrays) and actually cannot serialize other data types including Pytorch tensors. We eventually found a workaround at the operating system level, using fork() as a mechanism to achieve efficient one-shot, oneway IPC between a parent and child process, with copy-on-write concurrency. To materialize a record checkpoint, the main process forks and then immediately resumes model training; the child process serializes the checkpoint, writes it to disk, and then terminates. To prevent too many calls to fork(), we buffer up checkpoints and process them in batches of 5000 objects. Given the short lifespan of these child processes and an infrequent rate of forking due to batching, we have never seen more than two live children at any point in our evaluations-including in models that ran for many hours (Section 4).</p><p>In a technical report <ref type="bibr">[30]</ref>, we provide a more detailed discussion of the design and performance of our background materialization mechanism. This mechanism cuts logging overheads by 73.5% on average, according to our microbenchmarks <ref type="bibr">[30]</ref>. Execution speedups due to background logging are modest for workloads whose logging overheads are dominated by periodic checkpointing (&#120583; = 4.76% However, as we saw in Figure <ref type="figure">1</ref>, background logging can have a drastic effect when used for conservative logging (180% overhead down to 26%), since logging overheads account for a much larger fraction of end-to-end training times in those cases.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.2">Adaptable Periodic Checkpointing</head><p>In this section, we present a decision rule for dynamically calculating an appropriate checkpointing period or frequency. This condition is automatically tested by SkipBlocks to adapt the frequency of checkpointing to each training workload. For many developers, checkpointing once per epoch is a good default, but in general, the right checkpointing frequency depends on the training workload: e.g. how fast or slow the code executes relative to the size of its checkpoints. The goal of adaptable periodic checkpointing is to automatically materialize checkpoints as frequently as will increase expected replay speedups, subject to the constraint that record overhead does not exceed a user-specifiable limit.</p><p>Next we derive the invariants we use for adaptable periodic checkpointing. We refer the reader to the notation in Table <ref type="table">1</ref>.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>3.2.1</head><p>The Record Overhead Invariant. We require that the materialization overhead of a block is at most a small fraction of its computation time: &#119872; &#119894; &lt; &#120598;&#119862; &#119894; . This simplistic invariant is enough to ensure that record never exceeds a user-specifiable overhead (&#120598;), but it is all-or-nothing: a block is memoized always or never. Since blocks are often nested inside loops, and model developers may parallelize replay even with a small number of checkpoints (e.g. 2 checkpoints: 3&#215; parallelism), we need to relax our invariant to account for periodic checkpointing. Specifically, due to the nested loops structure of model training, we introduce &#119899; &#119894; and &#119896; &#119894; , as follows:</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>3.2.2</head><p>The Replay Latency Invariant. To avoid regret, recordreplay should always be faster than two vanilla executions (with neither overhead nor speedups). Even for hindsight logging workloads that do not permit partial replay, the speedups from parallel replay alone should more-than-offset the overhead incurred on record. Accounting for record overhead, we can assess each block &#119894; for this condition as follows:</p><p>The -1 in Equation 2 accounts for the fact that each parallel worker resumes from a stored checkpoint and does not need to compute its first iteration.</p><p>Because &#119866; is determined on replay and is not known during record, we satisfy the Replay Latency Invariant by testing Equation 3 instead. Equation 3 guarantees the Replay Latency Invariant as long as there is some parallelism (&#119866; &#8805; 2); we omit the details for brevity.</p><p>Because the time to restore is not known at record time, we assume that it is proportional to the time to materialize. Our naive assumption is &#119888; = 1.0, and this estimate is refined after observing materialization and restoration times from record-replay. In our case, the average scaling factor over all measured workloads (Table <ref type="table">3</ref>) turned out to be &#119888; = 1.38.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>3.2.3</head><p>The Joint Invariant. The Joint Invariant is automatically checked by SkipBlocks at record time for adapting the frequency of checkpointing. Blocks are tested after executing, but before materialization. By restricting memoization to blocks that pass the Joint Invariant test, flor simultaneously satisfies the Record Overhead and Replay Latency invariants. This follows from the fact that the Joint Invariant is derived by algebraic manipulation of the two invariants.</p><p>Note the &#119896; &#119894; + 1 in Equation <ref type="formula">4</ref>: this accounts for the fact that the test is performed after the execution of the block but before the materialization of its checkpoint. The goal is for the invariant to continue to hold if the checkpoint is materialized. We derive the Joint Invariant, Equation <ref type="formula">4</ref>, from Equation 1 and Equation 3. Both invariants are satisfied when the computed ratio, &#119872; &#119894; /&#119862; &#119894; , is less than the minimum of both thresholds.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.3">Instrumentation for Hands-Free Mode</head><p>As desired by the user, flor can instrument their model training code for automatic and efficient record-replay. The principal objectives of flor instrumentation are twofold:</p><p>(1) Memoization and periodic checkpointing by nesting loops inside a SkipBlock, and then statically estimating their sideeffects.</p><p>(2) Auto-parallelization of training replay by a syntax-directed transformation of loop iterators, enabling pseudoresume from partial checkpoints (Subsection 2.2.1).</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.3.1">Autorecording Model</head><p>Training. The first goal of instrumentation is to efficiently and correctly memoize loop executions for the model developer-without their intervention. flor memoizes loops because, in machine learning, they correspond to longrunning code, and unlike arbitrary "long-running code", loops can be detected statically. Ensuring correct and efficient memoization requires (i) capturing all of the loop's side-effects, and (ii) avoiding the capture of too many redundancies. Unfortunately, due to the language's dynamic features and extensive reliance on (compiled) C extensions, an exact and efficient side-effect analysis in Python is intractable <ref type="bibr">[21,</ref><ref type="bibr">41,</ref><ref type="bibr">52]</ref>. Past work overcomes Python's analysis limitations by restricting the expressiveness of the language <ref type="bibr">[7,</ref><ref type="bibr">26]</ref>, making some assumptions (e.g. that the variables don't change types <ref type="bibr">[9]</ref>), or relying on user source annotations <ref type="bibr">[60]</ref>. In a similar vein, we achieve efficient side-effect analysis by assuming that loop bodies in model training are predominantly written in PyTorch <ref type="bibr">[43]</ref>.</p><p>To the extent that loops deviate from our assumption, our static analysis will be unsafe (i.e. may misdetect side-effects), so we will automatically perform deferred correctness checks after replay and report any anomalies to the programmer. We find that our assumption holds frequently enough to be useful for hindsight logging purposes. Model developers do not typically build models or write training algorithms from scratch. Instead, they rely on popular machine learning frameworks such as PyTorch. Like many 3rd-party libraries, PyTorch has a well-defined interface by which it modifies the user's program in limited ways <ref type="bibr">[3]</ref>. The effects of PyTorch on the user's program are limited to (i) assignments and (ii) encapsulated state updates from method calls. As a result, all the side-effects of PyTorch code can be detected statically, with two notable exceptions: when an optimizer modifies a model, and when a learning rate scheduler modifies an optimizer <ref type="bibr">[4]</ref>.</p><p>First, flor estimates a set of changes ("changeset") for each block using the six rules in Table <ref type="table">2</ref>. flor walks the abstract syntax tree statement by statement, testing which rule is activated by each statement. The changeset for a block accumulates the individual changes of its member statements. Rules have a precedence such that at most one is activated per statement. Statements that activate no rule are ignored.</p><p>Next, flor performs a filtering step on the changeset to remove variables that are scoped to the body of the loop. flor removes from the changeset any variable that is defined in the body of the loop (henceforth "loop-scoped variable"), under the assumption that this variable is local to the loop and is not read after the end of the loop.</p><p>Finally, we make use of our encoded library-specific knowledge to augment the changeset at runtime (this is the only step that is not done statically). For PyTorch, it suffices to encode two facts <ref type="bibr">[4]</ref>: (i) the model may be updated via the optimizer; and (ii) the optimizer may be updated via the learning rate schedule. flor augments the changeset to include side-effects which were not detected by  A generator defines an iterator, and enables us to control global state between iterations of the main loop.</p><p>the rules, but which can be inferred from other elements in the changeset.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.3.2">Autoparallelizing Replay.</head><p>The second goal of instrumentation is to autoparallelize replay of model training, assuming partial checkpoints exist due to SkipBlocks. Replay instrumentation consists of wrapping the main loop's iterator inside a flor.generator (line 10 in Figure <ref type="figure">4</ref>), to model the pseudoresume behavior we covered earlier (in Subsection 2.2.1 and Figure <ref type="figure">3</ref>). We can identify the main loop at replay time, by having measured loop execution times during record. We define the longest-running loop as the main loop. Generators define an iterator by a series of yield statements, and allow us to control global program state between iterations of the main loop; namely, toggle the SkipBlocks from a skip state to a stepinto state between epochs (lines 3, 6 in Figure <ref type="figure">4</ref>). We implement parallel replay by having every parallel worker (NPARTS in total) execute the same instrumented code (as in Figure <ref type="figure">4</ref>), and flor sets PID to a different value for each worker so they work on distinct segments of the main loop.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>3.3.3</head><p>Deferred Checks for Correctness. As we have discussed, Python's dynamic features and extensive reliance on (compiled) C extensions, make an exact and efficient side-effect analysis intractable. flor's approach to detecting side-effects is efficient but unsafe: it may misdetect side-effects and thus fail to checkpoint sufficient state for correct replay. To mitigate risk, we automatically check that common user-observable state between record and replay matches <ref type="bibr">[5]</ref>. The standard training metrics that get logged by default (e.g. the loss and accuracy) form a fairly unique fingerprint of a model's training characteristics, so it's hard to perturb state or data that the model depends on without this being reflected in one of the model's metrics. Consequently, at the end of replay, we run diff, and warn the user if the replay logs differ from the record logs in any way other than the statements added for hindsight logging.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4">EVALUATION</head><p>To assess flor's ability to meet the goals of Section 1 in practice, we evaluated eight diverse machine learning workloads, taken from three separate benchmarks: classic computer vision, the General Language Understanding and Evaluation (GLUE) <ref type="bibr">[61]</ref>, and ML Perf <ref type="bibr">[36]</ref> (Table <ref type="table">3</ref>). </p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4.1">Flor Record Overhead is Low</head><p>We compared the overhead added by manual periodic checkpointing, at a rate of once per epoch, against the overhead added by automatic flor record (Figure <ref type="figure">5</ref>). We did not manually set the period for any of the flor record experiments. The checkpointing period was automatically calibrated by the mechanism in Section 3.2. flor record does not add significant overhead to training, so it may be enabled by default. Moreover, the flor instrumentation library is able to achieve the same effect as hand-tuned periodic checkpointing, with competitive performance, and without intervention from the user. For manual periodic checkpointing, we assume that each checkpoint is complete with respect to training. For flor record we only assume partial checkpoints: each checkpoint corresponds to the side-effects of the code block it memoizes (Section 2.1), but it may be incomplete with respect to training. Takeaway: flor record adds minor overhead, so it can be enabled by default. A novice model developer who uses flor can achieve similar performance to an experienced model developer.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4.2">Flor Record Overhead is Adaptable</head><p>Different model developers have different sensitivies to overhead.</p><p>In this section, we measured that flor record is able to adjust its checkpointing frequency to stay within the user-specifiable overhead limits (e.g. &#120598; = 6.67%). The nested training loops in most model training workloads are memoized every epoch by flor's adaptive checkpointing mechanism. This is because the time to materialize their checkpoints is negligible compared to the time it takes to execute them. In contrast, the sharp drop in overhead for fine-tuning workloads is due to their less frequent checkpointing  (Figure <ref type="figure">6</ref>) . Fine-tuning workloads are checkpointed less frequently because their loops have poor materialization time to computation time ratios. In other words, their checkpoints are massive relative to their short execution times. This is the case because the vast majority of weights are frozen in model fine-tuning, so a loop execution quickly updates a small fraction of values in an enormous model <ref type="bibr">[22]</ref>. Takeaway: Adaptive checkpointing drastically reduces overhead on model fine-tuning workloads (RTE &amp; CoLA), and ensures that no workload exceeds the user's overhead tolerance.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4.3">Flor Replay Latency is Low</head><p>In this section, we measure the replay speedups achieved by flor replay, assuming flor record checkpoints were materialized during training. Consequently, we measure the replay speedups when flor instruments model developers' code end-to-end for efficient hindsight logging-without intervention from the developer. Replay latencies are query dependent: they depend on the position of hindsight logging statements in the code. In cases when the model developer probes only the outer loop of training (as in line 13 of Figure <ref type="figure">7</ref>), partial replay can provide latencies on the order of minutes, even when model training takes many hours to execute. This is achieved by skipping unnecessary recomputation with loop memoization (e.g. skipping the nested training loop). The top subplot in Figure <ref type="figure">9</ref> shows outer-loop probe latencies for each of our models. Note the improvements range from 7&#215; to 1123&#215;-with the more significant improvements favoring the longer experiments (recall Figure <ref type="figure">5</ref>).</p><p>When the model developer logs data post-hoc from the inner training loop (as in line 10 in Figure <ref type="figure">7</ref>), then that loop must be re-executed on replay, and it will not contribute to savings from loop memoization. For these workloads, we will need to rely on parallelism to reduce latencies. We measured the hindsight logging latencies when a full re-execution of model training was necessary by running replay on multiple machines-this is shown in the bottom subplot in Figure <ref type="figure">9</ref>).</p><p>The parallel replay workloads used as many machines from the pool of 4 machines as would provide further parallelism gains. Each machine has 4 GPUs. In the limit, every epoch may re-execute in parallel, but the degree of parallelism may be increased even further by checkpointing additional state, which we leave as future work.</p><p>Takeaway: Assuming no work or guidance from the model developer, beyond the insertion of a couple hindsight logging statements, flor automatically parallelizes and conditionally skips computation on the re-execution of model training (Section 3.3.2). It achieves the greatest replay speedups from partial replay, but may scale out replay to multiple machines for further speedups.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4.4">Ideal Parallelism and Scale-out</head><p>Next, we compare the performance of parallel replay with checkpoint resume against parallel replay with checkpoint pseudoresume (refer to Section 2.2.1). An expert model developer, such as Judy, who does periodic checkpointing by-hand can ensure that the checkpoints are complete with respect to training. Thus, they can achieve the checkpoint resume performance. On the other hand, when flor instruments training code on behalf of the developer, it will rely on checkpoint pseudoresume, because as we discussed earlier, flor cannot automatically ensure that its checkpoints are complete with respect to training, and it assumes that the checkpoints are partial. Our results show that, although pseudoresuming training adds initialization overhead, this overhead is amortized through the course of parallel replay, such that there is a negligible difference between checkpoint resume and checkpoint pseudoresume.</p><p>In Figure <ref type="figure">10</ref>, we measured parallel replay performance, and observe it achieves near-ideal parallelism. Ideal parallelism is denoted by the gray horizontal line in each subplot. Because parallel workers do not need to communicate or coordinate, flor replay is especially  well-suited for elastic and horizontally scalable cloud computing, in which it can scale out to more GPUs at low marginal costs. This level of parallelism is achievable because model training replay is embarrassingly parallel given (complete or partial) checkpoints.</p><p>To assess our parallel performance, in Figure <ref type="figure">11</ref> we illustrate the near-ideal speedup as we add 4-GPU machines. We choose RsNt as our experiment because it has 200 epochs to parallelize. The modest gap between our results and ideal here is due to load balancing  checkpoint. When no complete checkpoint is available, it is possible to pseudoresume from a partial checkpoint. Although pseudoresuming adds initialization overhead to parallel replay, the cost is amortized over the course of replay, such that there is a negligible difference between checkpoint resume and partial checkpoint pseudoresume.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="5">RELATED WORK</head><p>ML lifecycle management. The machine learning lifecycle encompasses many tasks, including model design and development, training, validation, deployment, inference, and monitoring <ref type="bibr">[16]</ref>. There is a wide range of research and tooling being developed to support these many tasks. ML lifecycle management is especially challenging because it involves many cycles of trial-and-error <ref type="bibr">[27]</ref>, and its dependencies are hard to scope <ref type="bibr">[49]</ref>. When something goes wrong, ML engineers may need to rollback their model to an earlier version <ref type="bibr">[38,</ref><ref type="bibr">59]</ref>, inspect old versions of the training data <ref type="bibr">[23,</ref><ref type="bibr">25,</ref><ref type="bibr">35]</ref>, or audit the code that was used for training <ref type="bibr">[37,</ref><ref type="bibr">48]</ref>. Those activities require the proper management, versioning, and provenance tracking of data, models, code, and other context; existing solutions provide some support <ref type="bibr">[10,</ref><ref type="bibr">19,</ref><ref type="bibr">28,</ref><ref type="bibr">29,</ref><ref type="bibr">65]</ref>. Hindsight logging is a novel contribution in the lifecycle, and its minimalist, lowfriction interface makes it complementary to the prior work. flor is designed to be compatible with any of the tools in the Python ecosystem. In terms of training libraries, we have focused on Py-Torch, but adopting another training library involves only encoding any side-effects in the library's API (Section 3.3.1).</p><p>Model Debugging. There are many tools and techniques for helping users understand the behavior of their models <ref type="bibr">[2,</ref><ref type="bibr">34,</ref><ref type="bibr">46,</ref><ref type="bibr">47,</ref><ref type="bibr">50]</ref>, and for inspecting model internals <ref type="bibr">[31,</ref><ref type="bibr">42,</ref><ref type="bibr">45,</ref><ref type="bibr">57,</ref><ref type="bibr">58]</ref>. These techniques only inspect the models themselves, and are complementary to our work here, which focuses on the execution data generated while training the models.</p><p>The value of execution data is evidenced by widespread use of domain-specific loggers and visualization tools for that data, including TensorBoard <ref type="bibr">[17]</ref>, MLflow Tracking <ref type="bibr">[65]</ref>, and WandB [1]. Hindsight logging allows developers to keep their current logging practices and tools, but if they find they missed or forgot to log necessary execution data, we enable them to "query the past". Partial Materialization. Inspired by classical work on materialized views <ref type="bibr">[12]</ref>, a new body of work addresses partial materialization of state in ML workflows, to aid in iterative tasks like debugging.</p><p>As representative examples, Columbus <ref type="bibr">[66]</ref> accelerates the exploration of feature selection by choosing to cache feature columns; Helix <ref type="bibr">[63]</ref> focuses on choosing to cache and reuse the outputs of black-box workflow steps; Mistique <ref type="bibr">[58]</ref> focuses on techniques for compressing model-related state and deciding whether to materialize or recompute. These systems introduce bespoke languages for pre-declaring what to capture prior to computation; they also provide custom query APIs to interrogate the results. Hindsight logging is complementary: it enables post-hoc materialization in cases when it was not prespecified. Precisely because flor does not dictate a new API, it is compatible with this prior work: users of these systems (or any library with pre-declared annotations) can benefit from flor to add annotations in hindsight, and benefit from flor's efficient replay to add materialized state. At a more mechanistic level, some of the policies and mechanisms from this work (e.g., the model compression of Mistique) could be adapted into hindsight logging context to further improve upon our results.</p><p>Recovery and Replay Systems. Our techniques are inspired by literature on both database recovery and program replay. Hindsight logging is a redo-only workload, and we use a "physiological" approach <ref type="bibr">[18]</ref>: in our view, a model training script is a complete logical log (in the WAL sense) of a model training execution, and occasional physical checkpoints serve solely to speed up redo processing. Parallel and selective redo recovery was studied as early as ARIES <ref type="bibr">[39,</ref><ref type="bibr">62]</ref>. Parallelism in those techniques is data-partitioned and recovers the most recent consistent state; we are in essence time-partitioned and recover all prior states. In that sense our work bears a resemblance to multiversion storage schemes from POST-GRES <ref type="bibr">[54]</ref> onward to more recent efforts (e.g., <ref type="bibr">[32,</ref><ref type="bibr">40]</ref>). These systems focus on storing complete physical versions, which is infeasible in our setting due to constraints on runtime overhead.</p><p>Numerous program record-replay systems have been used in the past for less data-oriented problems. Jalangi is a system for dynamic program analysis that automatically records the required state during normal processing, and enables high-fidelity selective replay <ref type="bibr">[51]</ref>. This is achieved by identifying and storing memory loads that may not be available at replay time, using a "shadow memory" technique. Unlike flor, Jalangi replay has strict correctness guarantees. flor uses side-effect analysis rather than shadow memory because the former is lighter on overhead: in this sense, we risk replay anomalies to reduce record overhead and replay latency.</p><p>Prior work on Output Deterministic Replay <ref type="bibr">[5]</ref> makes a similar trade-off as we do. However that work pays for higher latencies to enable reproduction of nondeterministic bugs; we can avoid that overhead in Python model-training scenarios because sources of non-determinism (e.g. random seeds) are typically captured, and model-training frameworks are increasingly designed for reproducibility. An interesting line of work enables reverse replay with relatively high fidelity and without overhead by using memory dumps on a crash <ref type="bibr">[13]</ref>-this impressive result is made possible by the spatial locality of bugs in the vicinity of execution crashes; one complication with model debugging is that training errors, such as over-fitting, may not crash the program. We borrow the SkipBlock language construct from Chasins and Bodik's record-replay system for web scraping <ref type="bibr">[11]</ref>.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="6">CONCLUSION</head><p>At every step of exploration, model developers routinely track and visualize time series data to assess learning. Most model developers log training metrics such as the loss and accuracy by default, but there soon arise important differences between what additional training data model developers log-with major implications for data management.</p><p>In contrast to conservative logging, optimistic logging is an agile and lazy practice especially well-suited to early and unstructured stages of exploratory model development. In optimistic logging, model developers log training metrics such as the loss and accuracy by default, and defer collection of more expensive data until analysis time, when they may restore it selectively with hindsight logging. In the common case, or fast path, model developers get all the relevant information from the training loss, and move on. In exceptional cases, however, training replay may be necessary for post-hoc data restoration. In this paper, we documented a system of method for efficient record-replay of model training. Methodical hindsight logging consists of: (i) periodic checkpointing, (ii) block memoization, and (iii) checkpoint resume. To extend the benefits of methodical hindsight logging to novices and experts alike, we open source the flor suite for hindsight logging, which includes tools for: (i) low-overhead background logging, (ii) adaptable periodic checkpointing, and (iii) end-to-end instrumentation for efficient and fully automatic record-replay. We evaluated methodical hindsight logging to show that it achieves the goal of efficient record-replay, and then compared the instrumentation library provided by flor against the methodical expert-tuned approach, and find that the performance is comparable.</p></div></body>
		</text>
</TEI>
