Elamur Research

Classifying long legal documents using short random chunks

Paper · 2025 · Luis Adrian Cabrera-Diego

Summary

A legal document can run far beyond the amount of text a classifier can read at once. Reading from the start may miss useful passages, while processing the entire document can make a service expensive to run. This paper tests a different approach to text classification. It samples short passages from across a document, puts them back in their original order, and predicts the document type from that partial view. The authors built the classifier for Jus Mundi, where it needed to handle specialized legal text and run on in-house CPU servers.

The authors start with paragraph boundaries, splitting longer paragraphs into overlapping chunks capped at 128 tokens. A multilingual version of DeBERTa V3 encodes each selected chunk, and a long short-term memory network reads the resulting representations in document order. The authors compare sample sizes of 20, 48 and 62 chunks and test whether simple measures of document length improve the predictions. Training draws a fresh sample at each epoch, giving the classifier changing views of the same labeled documents. At test time, the authors repeat the evaluation over 30 runs so the reported scores reflect variation in which passages are drawn. DeBERTa V3

The evaluation uses a proprietary arbitration corpus covering 25 languages and 18 document classes assigned by legal experts. The best configuration on the test set reached a median weighted F-score of 0.898. It used 62 chunks and no explicit length features. The strongest configurations on the development set used 48 chunks and included length information. Most class-level median F-scores exceeded 0.800, with exceptions including Pleadings, Notice of intent and Settlement agreement. The errors show where short passages were less reliable, especially when related document types could be confused. The added length features did not improve classification of Notice of intent, one of the problems that had prompted the authors to try them.

The paper also describes a deployment with Temporal, which coordinates file discovery, validation and classification. On a CPU server with one worker of each type, the full workflow took a median of 498.080 seconds to process 100 randomly sampled test files. That timing includes handling the files as well as predicting their labels. The classification and deployment results answer different questions. The former shows that partial views carried enough evidence for strong aggregate performance on this corpus. The latter measures what it cost in time to turn files into predictions in the authors’ CPU setup.

Deep dive: Classifying long legal documents using short random chunks

Randomly sampled passages can classify long legal documents. The paper tests this approach on arbitration records and measures CPU deployment time. · about 33 minutes to read

The problem and its context

The type of a document and the cost of reading it

The task is to assign a type to an arbitration document. A set of pleadings, a witness statement and an expert opinion can all belong to the same broad legal domain. The classifier has to distinguish their roles using the classes defined for the collection. Shared legal vocabulary is part of the setting, while differences in wording, structure and length create possible clues. The work falls within the authors’ account of Legal AI, which includes tools for reducing repetitive work for legal professionals. How Does NLP Benefit Legal System?

Length affects the task in two ways. It makes a full reading more expensive, and it makes the choice of which passages to read more consequential. A short document may fit within the input that a classifier can process at once. In a longer document, a fixed cut at the input limit gives it the beginning and leaves everything after that cut unseen. Whether this is a good approximation depends on where the evidence for the type appears. An opening can establish what the document is, while a passage elsewhere might contain the language that distinguishes it from a related type. The authors frame this as a question about how much and which text a classifier needs for the decision.

A transformer uses attention to build representations that depend on context. In the input-length problem described by the authors, an encoder such as BERT becomes demanding in memory as the input grows. Legal pretraining addresses another part of the problem by exposing an encoder to specialized language. A document rich in legal vocabulary can still be too long for the resulting encoder to handle in a single pass. The paper treats adaptation to a domain and accommodation of long inputs as different design choices. Attention Is All You Need · BERT · LEGAL-BERT

The target setting also shaped which tradeoffs were acceptable. Jus Mundi wanted a classifier that could serve several tools and services, including ones where responsiveness mattered. The authors wanted to run predictions on CPUs or small GPUs so the cost of a production service would not depend on large accelerators. For documents that could contain private material, in-house execution gave the company a way to keep processing within its own infrastructure. The paper cites data use by some hosted services as a reason to care where the text goes.

Maintenance mattered alongside memory and hardware cost. A separate passage selector adds another learned component with its own behavior to maintain. A prompt-based service can require revisions when its set of classes changes or the service behind it is updated. The authors looked for a way to choose text without training a separate judge or maintaining a collection of prompts. Random sampling left them with a selection procedure governed by a sample size and a classifier that could learn from the views that procedure produced.

Ways earlier work handled long inputs

The paper describes several ways to split the work of reading a long document. In hierarchical classification, one component encodes short pieces, and another combines information across those pieces. The example the authors cite from Pappagari and colleagues divides text into chunks of 200 tokens and encodes them with BERT. An LSTM or a transformer layer then combines the chunk representations. Splitting keeps each initial encoding bounded. The second component can use evidence from several parts of a document even though they were encoded independently.

Another approach is to spend the available input on passages judged informative. CogLTX uses a trained judge to identify sentences for its classifier. Park and co-authors examine how two approaches differ in the way they supplement a document’s opening 512 tokens. One chooses sentences with TextRank, which ranks them by relevance. The other draws sentences randomly. That comparison gives the authors a reason to take random selection seriously. It also preserves a prominent role for the opening of the document, since both alternatives add material to a prefix. Removing that fixed prefix from the design changes which evidence can be counted on to appear.

A separate line of work changes how attention operates so an encoder can accept longer sequences. Longformer combines attention over a local window with global attention for selected positions. The paper describes it as able to process up to 4,096 tokens. This addresses the length problem within the encoder itself. The authors also note the processing time and memory demands that can accompany these longer inputs, which matter when the target deployment must fit modest hardware. Longformer

Legal document research had used both hierarchical encoders and adaptations for longer sequences. In the work on EU legislation cited by the authors, legal Doc2Vec representations feed a bidirectional recurrent network with attention specific to each label. A related study uses legal Doc2Vec representations with a bidirectional LSTM and attention over chunks. These designs combine information at the document or chunk level and give the prediction component ways to weight what it reads. Large-Scale Multi-Label Text Classification on EU Legislation · Doc2Vec

LegalDB and Lawformer start from existing encoders and adapt them to use the Longformer approach, with pretraining on legal text. LegalDB starts from DistilBERT, and Lawformer uses a Chinese RoBERTa encoder. Another cited effort adapts LegalBERT both into a hierarchical system and into a legal Longformer that can take up to 8,192 tokens. These examples illustrate how domain specialization and input length can be pursued together. DistilBERT · Lawformer · RoBERTa

Other earlier studies change what is passed to the classifier. The document-to-graph approach represents extracted relations as graphs and classifies from those representations. The contract classification work by Li and colleagues filters short sections with logistic regression before passing them to a fine-tuned RoBERTa classifier. Trautmann’s prompt-chaining approach recursively summarizes sections to prepare a document summary and uses that summary with a prompt that includes examples. All three approaches transform or select evidence before the final decision, with different demands on computation and maintenance.

These precedents give the current paper a narrower question than whether complete legal documents contain useful evidence. The question is whether arbitrarily located passages can supply enough of that evidence for the class distinctions Jus Mundi needs. The authors cite earlier observations that classification can succeed from part of a document, including cases where random selection is competitive with more elaborate methods. They then put the hypothesis to work in a setup where the document can be long, the language can vary, and the deployed system must be able to run on a CPU.

The method, step by step

Choosing passages from the whole document

The method starts by turning a document into a collection of candidate chunks. The original files were in HTML, so elements for paragraphs and list items could supply boundaries. This matters because the units drawn at random are prepared from the document’s structure. The procedure starts from paragraphs, and an individual draw selects a prepared chunk. A long paragraph can contribute several candidates.

Each paragraph goes through DeBERTa V3’s tokenization procedure. Tokens are the text units the encoder receives. The preparation step also encodes them in the format the classifier expects. When a paragraph produces a chunk longer than 128 tokens, the authors split it again. They describe the subdivision using an overlapping stride of 16 tokens. With overlap, a subdivision can share some context with its neighbor at a cut. The upper limit applies to a chunk, while the sample size governs how many chunks can enter the document classifier.

The sampling pool is the document’s complete set of encoded chunks. The authors explore sizes of 20, 48 and 62. The settings of 20 and 62 came from quartiles of paragraph counts in the corpus. A quartile is a point in an ordered distribution, so those values tie the choice of budgets to how many paragraphs documents tend to contain. The authors chose 48 without that quartile rationale. The corpus quartiles describe the original paragraphs. Because tokenization and subdivision can give a long paragraph several chunks, those quartiles and the later distribution of candidate chunks describe different things.

After the draw, the selected chunks are placed in the order they occupied in the document. For instance, when the sample includes material from both the opening and a later section, the opening material goes to the classifier first even if the later chunk was drawn first. The decision about what to include is random. The sequence in which the classifier receives that evidence reflects the document. This preserves relative position among the selected passages. The skipped text can still leave gaps between successive entries in the sequence.

The mechanism gives long documents and short ones the same kind of input representation: a sequence of bounded chunks. For a long file, it also bounds the number of chunks the classifier is asked to encode at a given setting. The preparation stage still needs a pool of candidates from which to draw. Accordingly, the chunk budget describes what enters contextual encoding and aggregation. File handling and preparation remain part of the work needed to reach that stage.

From a legal document to a class prediction

The steps in order.

From a legal document to a class predictionStep 1: Split the document at paragraph and list boundaries1. Split the document at paragraph and list boundariesStep 2: Tokenize paragraphs and subdivide long chunks with overlap2. Tokenize paragraphs and subdivide long chunks with overlapStep 3: Sample chunks and restore their document order3. Sample chunks and restore their document orderStep 4: Encode each chunk and pool its contextual representation4. Encode each chunk and pool its contextual representationStep 5: Combine the ordered representations with an LSTM5. Combine the ordered representations with an LSTMStep 6: Append document length features when enabled6. Append document length features when enabledStep 7: Score the classes and predict the document type7. Score the classes and predict the document type

From chunk representations to a class

The first learned stage processes each selected chunk with multilingual DeBERTa V3. The encoder assigns each token a vector, a collection of numerical values that the next stage can use. The values are contextual because they depend on the other tokens in the chunk. The same term can therefore contribute different contextual information in different passages. At this stage, the encoder computes that information within the selected chunk.

The architecture uses the representation at the chunk’s first position, the special [CLS] token. A dense layer and a GELU activation process the representation. The dense layer learns how to combine the values in the vector. GELU applies a nonlinear transformation to the result, allowing the combination used downstream to depend on more than a weighted sum alone. The paper calls this operation context pooling. Its output is a vector for the whole chunk, so the next stage can work through the document using a sequence of vectors in place of a sequence of all selected tokens.

A long short-term memory network, abbreviated LSTM, takes these vectors in document order. It is a recurrent network, which means it carries a state from one input position to the next. In this classifier, each position corresponds to a pooled chunk. As the network receives another chunk vector, it can update its state using both that vector and the state built from the preceding ones. The final state serves as the representation of the sampled document for the class decision.

There are two levels of context here. DeBERTa V3 builds a representation from the tokens that appear together within a chunk. The LSTM combines evidence across chunks after each has been reduced to a pooled vector. Thus a later passage can affect the decision in combination with earlier sampled material, while the individual token representations from those passages were computed separately. The order helps the LSTM process evidence in its original sequence. The architecture described in the paper gives the LSTM the pooled vectors, with no stated input indicating the length of an omitted gap between them.

The final state can be extended with length features. A dense layer then turns the resulting representation into scores for the document classes. A softmax activation converts those scores into relative class probabilities that sum to a whole, and the classifier uses the resulting distribution to determine the predicted type. The pooler and LSTM build the representation used for classification. The last dense layer and softmax connect that representation to the classes assigned by the legal experts.

What the length features add

The authors considered features that describe the entire document, even when the text input shows only a sample. The first is the character count, written as n_c. The second is the original paragraph count, n_p. The third is an estimate of the page count. The authors lacked actual page counts for some of the files, so they used a standard-page character allowance to derive an estimate.

aₚₚ = n꜀ / 1,800

Here aₚₚ is the approximate page count, and n꜀ is the number of characters in the document, written elsewhere as n_c. The equals sign defines the estimate. The slash denotes division, and 1,800 is the number of characters the paper assigns to a standard page. The estimate expresses text volume in page units, so the values are meaningful without access to the original pagination.

Before supplying the features to the classifier, the authors take the natural logarithm of each. The logarithm compresses a wide range of counts so differences at the large end of the original scale occupy less space in the transformed values. The character count and estimated page count are mathematically related because the latter is derived entirely from the former. Taking their logarithms preserves that dependence. Paragraph count describes a different property of the document because paragraph lengths can vary.

When a setting includes length features, their transformed values are concatenated to the final LSTM state. Concatenation joins the values into a single input for the last dense layer. The features do not tell the sampler where to draw chunks, and the chunk encoder still receives the same form of text input. Instead, the final decision can use a global length signal alongside the evidence gathered by the LSTM. This placement matters when interpreting comparisons with and without the features. The change concerns the inputs to the final decision, while the sampling mechanism and the architecture for processing text remain the same kind of system.

Expert advice supplied a concrete reason to try this addition. The legal team expected length to help distinguish some related types. A short sample from a very long document can look much like a sample from a shorter one, particularly if the passages use similar expressions. Whole-document length gives the decision layer a way to account for that difference. Whether the signal helps depends on how the labeled examples are distributed and on what the text already reveals.

Training with a changing view of each document

The corpus was divided into training, development and test data before the evaluation described in the paper. The training labels describe complete documents. A draw of chunks inherits its document’s label because the classifier is asked to predict the type of the source document from that view. A passage can contribute little evidence by itself and still occur in a document with a clear label. The architecture is trained to make the decision from the collection of sampled passages.

An epoch is a pass through the training data. At the start of each epoch, the authors resample the chunks for the documents. A fresh draw lets a document contribute different passages over the course of training, while its class stays the same. This changes the examples the classifier sees without requiring experts to add labels for individual chunks. The intent is to make the classifier usable with a range of partial views of a legal document.

Resampling also aligns what happens in training with what happens at inference, when the system predicts a label for an input file. A deployed prediction can use a sample that differs from any particular training view of the same kind of text. Repeated test evaluation takes this behavior seriously. A fixed set of test labels can produce different scores across runs because the classifier receives different evidence about those documents. In the paper, this variation is part of the evaluation design.

The reported training hardware was an NVIDIA A100 80Gb. That is the environment for training the classifier. In-house CPU operation is an objective for the service that uses the trained classifier to make predictions. Training and deployment are distinct stages with different resource demands. The experiments on larger samples also show why that distinction matters. Increasing the number of chunks changes the work involved in learning as well as the work of predicting a class.

Taking a directory of files through the service

The deployed pipeline wraps the classifier in Temporal, a durable workflow orchestrator. A workflow coordinates the operations needed to finish a request. An activity is a unit of work within it, a queue holds work until it can be processed, and a worker executes the activities or workflows it is configured to handle. A Temporal client can submit a workflow and wait for its result or obtain an identifier with which to check its status later. An independently deployed API sends work into this arrangement.

The first activity, a₁, finds JSON files in a directory and returns their paths. The second, a₂, reads and validates an individual file. The third, a₃, prepares the input and calls the classifier. The authors keep input preparation and prediction together because separating them would require extra conversions across the activity boundary. They describe a sequence that would turn tokenized and encoded text into NumPy arrays, serialize the result to JSON, and then parse it to build a tensor for PyTorch. Keeping that work within the classification activity avoids the intermediate transfer.

A workflow named w₁ calls the validation and classification activities. It arranges the files in batches of 10 documents and starts a fresh workflow instance when a batch is complete and more files remain. Starting a fresh instance keeps the event history from growing with the entire directory. The outer workflow, w₂, calls the discovery activity and then starts w₁ on the resulting file list. The system can therefore accept a directory even though it manages processing in smaller groups internally.

The input and output queue, Qᵢₒ, is handled by worker type W₁. That worker handles discovery and validation and executes the outer workflow and the relevant parts of the inner one. The dedicated classification queue, Q꜀, is handled by worker type W₂, which executes the preparation and prediction activity. By assigning the queues this way, the authors can add instances of the worker that handles the work they want to scale. A workflow or activity handles an input at a time, and Temporal can run multiple instances concurrently when the worker configuration permits.

The workflow batch and the classifier’s document input have different meanings. The batch of 10 controls how the workflow groups documents. Inside the classification activity, the deployed classifier processes a single document at a time. That document may itself be represented by many chunks. Thus a directory request, a workflow batch and a sequence of chunks are distinct units. Each shapes a different part of the service’s behavior.

Experiments and results

The corpus and the evaluation splits

The corpus consists of proprietary legal arbitration documents in 25 languages. Legal experts assigned the documents to 18 classes over multiple years. Some documents existed in more than one language. The authors retained one version for such cases and gave preference to languages outside the most common ones. The paper names English, French, Spanish and Portuguese as those most frequent languages and gives document counts of 9,378, 1,602, 998 and 255 respectively. The treatment of multilingual versions is relevant to what the evaluation measures. Each retained document contributes a view in its selected language, rather than all its translations appearing as separate observations.

The training split contained 80% of the data, the development split 10%, and the test split 10%. The splits were stored as JSONL, a format that represents records on separate lines. Training is where the classifier learns from the labels. The development split is used to compare configurations during training. The test split is used to measure performance on held-out documents. The test set contained 1,229 documents, a count the paper also gives when describing the GPU timing workload.

Document lengths vary even within the same legal domain. The median for the full corpus was approximately 7.3 pages. Expert opinion was the class with the longest documents by the median length reported in the paper, roughly 38.8 pages. The shortest class by that measure was Other, with a median of 1 page. All of these values are estimates derived from character counts. They show why length could plausibly help in some distinctions while also showing why the amount of sampled text represents a different share of different documents.

Class frequencies were uneven. Some classes in the development and test splits had as few as 14 documents. That matters both for the headline metric and for the separate class-level analysis. An aggregate score can be strong even when a less frequent class is difficult to identify. The paper also explains how the corpus was obtained. It includes material written by the legal team and documents obtained from public sources, collaborations and partnerships that permitted the intended training use. Experts anonymized sensitive material before the developers had access to it.

What the comparisons measure

The paper assesses classification with a weighted F-score. An F-score combines precision and recall. For a given class, precision concerns how often a prediction of that class is correct. Recall concerns how often documents labeled with that class are recovered by the classifier. Weighting by class support gives classes with more labeled examples greater influence on the aggregate. The authors chose this measure because of the imbalance in the data and also examined class-level F-scores to see how the aggregate was distributed across document types.

The quantitative comparisons on this corpus are among settings of the proposed classifier. They vary the number of sampled chunks and which length features reach the final decision layer. The results table focuses on the strongest development configurations and also includes the setting with the smallest sampling budget. Its caption identifies the best five by development performance. The systems described as earlier work provide context for the design, while the paper gives no scores for a head-to-head run against those external classifiers on this test split. The small-budget setting is the clearest internal reference for how far the method can go with less text.

A development score is calculated during training. The paper says that each epoch had a single development evaluation, so a particular draw of chunks contributed to that score. For test evaluation, each setting was evaluated over 30 runs. The same held-out collection supplies the labels across runs while random chunk selection changes the input. The paper reports a distribution over those runs and uses its median as a measure of typical performance. The notation Q₂ in the results table refers to that median.

This procedure distinguishes sensitivity to the sample from variation in the makeup of the test set. If a classifier sees different passages from a test file on different runs, the predictions may change even though the file belongs to the same class each time. Repeating the procedure makes the reported score less dependent on whether a particular run happened to draw informative passages. The result is a distribution of scores for the tested classifier and split, with randomness coming from which parts of the documents it reads.

Classification performance

The best test result reported in the paper is a median weighted F-score of 0.898 over 30 runs. The configuration identified as best on the test set samples 62 chunks and omits explicit length features. The two leading development configurations identified in the class-level analysis use 48 chunks. One includes paragraph count, character count and estimated page count, and the other includes character count alone. The paper’s description of a 48-chunk classifier and its identification of the strongest test configuration therefore refer to different settings in the same family.

The authors report that the displayed test distributions generally had limited variation and that development scores were close to the test medians. The configurations did change order between development and test. This is possible when a development score is based on a single sampling run per epoch and a test summary is based on repeated draws. It can also reflect differences between the documents in the two splits. The two rankings show how each condition turned out. They give separate answers to which setting scored best during development and which had the strongest median on test.

A sample of 20 chunks produced lower performance and still gave results the authors considered usable for many tasks. That setting matters because it shows the classifier drawing evidence from a smaller reading budget than those of the leading settings. The discussion supplies the qualitative comparison. It does not give a numeric score for that configuration in the prose, so the size of the performance change cannot be stated from the reported values there.

The per-class results give a more specific view of what the system could classify. They use medians over the same 30 test runs for the leading development and test settings. Most class-level median F-scores were greater than 0.800. Pleadings, Notice of intent and Settlement agreement were among the exceptions. Notice of intent and Settlement agreement were also among the less frequent classes during training. Pleadings was frequent, so the difficult cases include both sparsely represented and commonly encountered types. The errors between particular pairs help explain why a result for the corpus as a whole leaves important questions about its classes open.

Timing the workflow and GPU prediction

The CPU deployment experiment timed 30 Temporal pipeline runs. Each run received 100 documents sampled randomly from the test split. Changing the files exposed the workflow to different combinations of types and lengths. The test also let the authors see how their batch design behaved when the workload varied. The server used CPUs only, with one instance of the input and output worker and one instance of the classification worker. The measured time included the reading and validation of files as well as classification.

The median end-to-end elapsed time for a CPU run was 498.080 seconds for 100 files. The authors also report an approximate per-file time of 4.98 seconds for this CPU measurement. This is derived from the batch-oriented workload they describe. The paper separately reports a median time of 68.002 seconds for an NVIDIA A100 to predict the full test split of 1,229 documents, calculated over more than 300 runs. The GPU number describes prediction on the full split. It does not establish a matching end-to-end workflow measurement with the same file handling, document count and worker setup as the CPU runs.

Median elapsed seconds for CPU workflow and A100 prediction on arbitration test documents

The A100 prediction run took less time under a different workload and timing scope.

Median elapsed seconds for CPU workflow and A100 prediction on arbitration test documentsNVIDIA A100 prediction on the full test split: 68.002NVIDIA A100 prediction on the full testsplit68.002Deployed CPU workflow on sampled test files (this paper): 498.080Deployed CPU workflow on sampled testfiles (this paper)498.080
The numbers
System or settingmedian elapsed seconds per run
NVIDIA A100 prediction on the full test split68.002
Deployed CPU workflow on sampled test files (this paper)498.080

The distinction between the workloads matters when reading the chart. The CPU result describes the service that takes files through a workflow. The GPU result describes a prediction run on a different set size, with its own run count and timing scope. Both are medians for work on the arbitration test data. The comparison shows the elapsed times the authors observed under their respective conditions. A controlled hardware comparison would time the same work with the same boundary around the measured operation.

The deployment analysis also reports the authors’ experience getting the workflow running. A functional local version took around 2 hours to develop, excluding the time to read documentation and deploy the orchestrator. They had a more robust version ready for their servers in less than a week. These figures describe their own development experience. The operational observations explain what the orchestrator supported in that setup, including retries, history inspection, queueing and worker placement.

What the ablations show

Reading fewer or more passages

The paper’s most direct comparison varies the number of sampled chunks. The lower-budget configuration uses 20. The settings of 48 and 62 provide more opportunities for useful passages to enter the sample, with the strongest test median observed at 62. The lower performance of the 20-chunk setting is consistent with useful evidence being missed more frequently when less text is read. The paper does not track whether any particular identifying passage was present in a draw, so this explains a possible mechanism for the result without establishing that mechanism file by file.

The results address whether the classifier can work when it sees a limited selection of chunks. They offer less detail on the precise relationship between budget and score. The leading settings differ in their length features as well as in the number of chunks, and the results presentation emphasizes settings that performed well in development. Comparing the strongest development and test configurations therefore combines a change in sampling budget with a change in feature input. The best observed test setting is evidence that 62 chunks worked well in this corpus. Its ranking alone cannot identify the contribution of the larger sample while holding everything else fixed.

The authors also explored budgets up to 160 chunks. They partially managed to train configurations using 80 and 120. Those attempts took longer, used more memory and did not yield better results than the configurations presented in the comparison. The incomplete training makes these experiments useful as evidence about practical difficulty in the authors’ setup. It leaves open how a fully trained larger-budget classifier would perform, or whether a differently configured system could use a larger sample effectively. In practical terms, extra passages came with a resource cost before they demonstrated any score benefit.

The unit being changed is the number of selected chunks. Since chunks can be shorter than the token cap, increasing that budget does not add a uniform quantity of text across documents. It does not give the same proportional increase in coverage for a short file and a long file either. The useful comparison is between the configured budgets and their observed outcomes on the corpus. The paper does not establish a particular fraction of a document that the classifier must read to make a dependable prediction.

How much information does length add?

Notice of intent and Notice of Arbitration motivated the length-feature experiment. The authors were having difficulty separating the two types because they are similar in structure. The legal experts expected a Notice of intent to be shorter than a Notice of Arbitration. If that pattern held among the labeled examples, a global length input could be helpful when both types supplied similar text chunks. The corpus statistics did not support the expected length distinction. Adding length features also did not improve classification of Notice of intent.

The lack of improvement is specific evidence against the proposed remedy for this confusion in the tested setup. It leaves open whether length helps other class distinctions. Both leading development configurations included length information, and the strongest test configuration omitted it. That combination of results rules out a simple reading in which the extra signal consistently improves the classifier. It also gives no basis for claiming that length always harms predictions. The most direct conclusion concerns Notice of intent, the exact class the authors wanted the new features to help.

Character count and the estimated page count are two encodings of the same underlying quantity. Their joint presence in a configuration does not add independent evidence about how long a document is. Paragraph count captures something different, since documents with comparable amounts of text can use different numbers of paragraphs. The comparisons show the performance of the tested combinations. They cannot isolate a separate contribution from estimated pages as though that feature were gathered independently of the character count.

The authors raise two possible explanations for the difficulty with Notice of intent. The class has relatively few training documents, and some of its labels could contain annotation errors. They suggest that labeling errors could also help explain why the corpus length statistics disagree with the legal team’s expectation. This is a hypothesis about where to look. The paper does not report a review establishing that the labels are wrong. The observed facts are the class’s difficulty, the failure of the added features to improve it and the mismatch between the length expectation and the corpus statistics.

How errors group by document type

The paper’s examination of recurring confusions gives a reason to look beyond class frequency and length. Pleadings performed poorly in spite of being frequent. The authors describe some Notice of request and Other requests documents as sometimes being treated as Pleadings. That pattern shows how an error at a boundary can lower performance on a common label. A class can supply many training examples and still be hard to distinguish if related types look similar under the evidence the classifier receives.

The authors also report occasions when the classifier predicted Witness statements for Expert opinions. Expert opinion had the longest median document length among the reported classes, and yet the confusion appeared with and without length features. Likewise, Settlement agreement was sometimes predicted as Contracts despite a difference in document length in the corpus statistics. These are examples in which a length difference at the class level was insufficient to prevent errors on individual files.

A class median describes a typical point in its length distribution. It cannot tell the classifier the type of every document near that point, and two types with different medians may still have individual files of similar lengths. At prediction time the classifier has the character count or paragraph count of the file in front of it, when those features are enabled, plus a sample of its wording. The paper’s error analysis shows which class boundaries remain vulnerable using that evidence. It leaves the explanation for any individual error to a closer reading of the document and its label.

These cases also show why class-level F-scores complement the weighted result. A class can lose precision when files from nearby categories are predicted as belonging to it. It can lose recall when its own files are predicted as belonging to a neighboring class. The weighted score pools effects across categories, giving greater influence to those with more examples. The class scores and the examples of confusion give the reader a way to see which decisions require more care than the overall median would suggest.

What repetition shows about random sampling

The repeated test runs probe a particular source of uncertainty. Since the inputs are redrawn, a narrow spread of aggregate scores means the classifier’s overall behavior on the test split is reasonably stable under those redraws. The authors interpret this as evidence that changing the samples during training helped make the classifier robust. The practical observation is that the trained settings generally produced limited variation in the weighted F-score when tested repeatedly.

Attributing the stability to resampling during training requires a comparison that holds the rest of the procedure steady. The paper does not report a matched configuration trained on the same fixed subset of chunks at every epoch. Other properties of the task could also contribute to stable aggregate scores. A document type might leave clues in multiple places, for instance, or variation among individual files could cancel out in a corpus-level measure. Those are possible explanations, and the study does not measure their separate contributions.

Aggregate stability also leaves room for instability at the level of a single prediction. The same overall weighted F-score can result when a redraw helps with one set of documents and hurts on another. Per-class medians give more detail about where performance was persistently weaker. They still summarize across files and runs. The evaluation therefore provides evidence about the robustness of aggregate performance to reading different sampled text, with less evidence about how often a particular file changes predicted class across draws.

What the workflow tests add

The deployment runs vary the mix of files as well as engaging the sampling mechanism within the classifier. A timing run may receive a different combination of document lengths and types from the one before it. The resulting median gives a view of how the pipeline behaved across those mixtures under the authors’ worker configuration. The experiment is a practical check of the running service. It does not isolate the time attributable to each activity or determine how much the median would change with another worker count.

Temporal’s history supplied a different kind of analysis. The authors could see when work entered a queue, when a worker picked it up, when it ended and whether an error led to a retry. The paper illustrates the workflow continuing after an activity failed. The intended response depends on the cause. A file that cannot be read or has the wrong format can be marked as a failure without repeating that same work. When a worker stops responding, the activities affected by its failure can be retried up to a configured count, referred to by the authors as n. Here n stands for the permissible number of retries, with no specific value stated.

Message size influenced the design as much as the processing graph did. According to the authors, requests are capped at 2MB and event history at 4MB. Grouping documents into batches of 10 and renewing the workflow instance helps manage those constraints. The paper says that payload encryption and decryption were straightforward to add. The timing and history observations describe the resulting deployment. They give a record of operating it in the tested conditions, while capacity and resilience under larger loads would require other measurements.

Limitations

Limits the authors identify

The authors report that training with larger samples was difficult. Their partial attempts at larger budgets used more memory and took longer, without showing a better result. This shaped which configurations could receive a full comparison. The strongest reported test result is therefore the strongest among the completed settings the authors discuss. The work gives practical evidence about what fit their experiments, with the larger-budget part of the design space still open.

They also note a limitation in development evaluation. A single evaluation per epoch lets the selected chunks affect the score used to judge that checkpoint or setting. The test results are summarized over repeated evaluations, so the development ranking and test ranking rest on signals of different stability. The authors plan to perform several development evaluations during training. That would make the development estimate more comparable in spirit to the test median, while differences between the splits would still matter.

The authors identify unresolved questions about the errors. The legal team’s expectation about the length of notices did not match the dataset statistics, and Notice of intent remained difficult to classify. They propose a closer analysis of misclassified documents with the legal team. They also plan to investigate the language of the document as a possible contributor to errors and aggregate performance. This distinction matters in a corpus whose language counts are highly uneven. A pooled result establishes performance over the observed mix while leaving the performance by language unanswered.

The service also has limitations the authors intend to address. Its classifier processes one document at a time even though the workflow manages batches of files. The authors want to improve batching at the classifier level. They also propose moving from PyTorch to ONNX Runtime, exploring quantization and using Zstandard to compress workflow messages so batches can fit within the payload budget. These are plans to improve deployment. The reported CPU timing comes from the existing implementation.

The length estimates are approximate. The paper explains that actual page counts were unavailable for part of the corpus, so it converts character counts using the standard-page convention. This is enough to compare the volume of text using a consistent scale. It cannot account for how the original files were laid out or how much space tables, exhibits and formatting occupied. The feature analysis should consequently be understood as an analysis of text length and paragraph count.

Limits that follow from the experimental setup

The evaluation establishes feasibility within one proprietary arbitration collection and its expert-defined classes. Other legal collections can differ in how documents are structured, how types are defined and where the clues for each type occur. A classification task may rely on language repeated across a document, which gives random draws several opportunities to capture it. A task whose decisive evidence appears in one brief passage could be more sensitive to what the sample misses. The arbitration results do not measure the difference between those situations.

The sampling procedure also depends on candidate boundaries that were available in the original HTML. Paragraphs and list items are an input to the method. When files arrive in a form where those boundaries are less accessible, candidate construction may change. The authors discuss the classifier as part of a larger pipeline that is intended to work alongside tools such as OCR and metadata extraction. The CPU measurement covers the current processing workflow for JSON files. It does not quantify the effect of OCR quality or paragraph reconstruction on classification.

The paper gives no direct comparison on this corpus between random selection and a fixed prefix, a learned passage selector, or a classifier that sees the entire available document. The tested settings show how the proposed family performs at several reading budgets and with different length inputs. They do not determine how much accuracy or time random sampling gains against those alternatives under matched conditions. Earlier findings support the choice to test the approach, while the evidence about this corpus comes from the authors’ own configurations.

Other components of the classifier are also not independently varied in the reported comparisons. The paper does not compare the LSTM with simple pooling of the chunk vectors, test the effect of shuffling the selected chunks, or show the result of removing the overlap between subdivisions. The architecture has a clear reason for each of these choices. Their exact contribution to the observed F-score remains unmeasured. In particular, restoration of document order gives the LSTM access to relative sequence, but the experiments cannot say how much of the success depends on that order.

The biggest score is a median across redraws of the held-out inputs. It is not an estimate of how frequently a particular document will receive the same label in a live service, and the per-class medians do not answer that question either. Such a measure would need to follow individual documents across runs. That would distinguish consistently hard documents from documents whose predictions depend strongly on which chunks happen to be seen. The distinction is relevant for a service in which the sample can change when the same file is classified again.

The narrow class definitions and the quality of annotations also matter. The legal experts supplied the target labels, and the reported scores measure agreement with those labels under the chosen splits. Confusions can reflect incomplete sampled evidence, similarity between types, inconsistency in labels, or some mix of these. The notices with an unexpected length relationship are the authors’ example of why label review could matter. The paper leaves the underlying causes open because it does not document a systematic adjudication of the errors.

Finally, the timing results describe whole runs at the reported workloads and worker counts. They leave unanswered how queue delay, document length and concurrency affect the time a caller waits for an individual response. The paper describes how additional workers could be deployed and how Temporal can continue after certain failures. Those are properties of the design and observations from its operation. The timing experiment does not measure scaling under added workers or the distribution of delays at a sustained request rate. Likewise, the ability to run in-house and encrypt payloads addresses aspects of the authors’ privacy objective, while the study does not evaluate the privacy properties of the complete service.

What came after

There is no identified follow-up study to trace here. The next steps described in the paper are the authors’ own plans. The engineering work concerns faster inference, larger workflow batches and processing multiple documents together in the classifier. The analysis they propose addresses a different question: which documents and languages account for the remaining errors. A review with legal experts could help distinguish ambiguous or inconsistent labels from cases where a partial view contains too little evidence. The published results leave both the operational improvements and the detailed explanation of those errors to future work.

Cite

Cite as Luis Adrian Cabrera-Diego. 2025. Classifying long legal documents using short random chunks. arXiv:2512.24997.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.48550/arxiv.2512.24997 · arXiv 2512.24997

@misc{cabreradiego2025classifying,
  title = {{Classifying long legal documents using short random chunks}},
  author = {Luis Adrian Cabrera-Diego},
  year = {2025},
  doi = {10.48550/arxiv.2512.24997},
  eprint = {2512.24997},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2512.24997}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/cabrera-2025-diego-classifying-long-legal-documents-using/

References

29 references, from the paper's own bibliography.

  1. Haoxi Zhong, Chaojun Xiao, Cunchao Tu, Tianyang Zhang, Zhiyuan Liu, Maosong Sun. 2020. How Does NLP Benefit Legal System: A Summary of Legal Artificial Intelligence. Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics. doi:10.18653/v1/2020.acl-main.466. our card
  2. Robert Dale. 2019. Law and Word Order: NLP in Legal Tech. Natural Language Engineering. doi:10.1017/S1351324918000475. OpenAlex ↗ · Scholar ↗
  3. Jay A Mitchell. 2014. Document appreciation: some characteristics of legal documents (and talking with students about them). SSRN. doi:10.2139/ssrn.2406047. OpenAlex ↗ · Scholar ↗
  4. Dietrich Trautmann. 2023. Large Language Model Prompt Chaining for Long Legal Document Classification. https://arxiv.org/abs/2308.04138 OpenAlex ↗ · Scholar ↗
  5. Ilias Chalkidis, Manos Fergadiotis, Prodromos Malakasiotis, Nikolaos Aletras, Ion Androutsopoulos. 2020. LEGAL-BERT: The Muppets straight out of Law School. Findings of the Association for Computational Linguistics: EMNLP 2020. doi:10.18653/v1/2020.findings-emnlp.261. our card
  6. Vedangi Wagh, Snehal Khandve, Isha Joshi, Apurva Wani, Geetanjali Kale, Raviraj Joshi. 2021. Comparative Study of Long Document Classification. TENCON 2021 - 2021 IEEE Region 10 Conference (TENCON). doi:10.1109/TENCON54134.2021.9707465. OpenAlex ↗ · Scholar ↗
  7. Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova. 2019. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers). doi:10.18653/v1/N19-1423. our card
  8. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, \textbackslashLukasz Kaiser, Illia Polosukhin. 2017. Attention is all you need. Advances in neural information processing systems. our card
  9. Karla Grossenbacher. 2023. Employers Should Consider These Risks When Employees Use ChatGPT. Bloomberg Law. https://news.bloomberglaw.com/us-law-week/employers-should-consider-these-risks-when-employees-use-chatgpt OpenAlex ↗ · Scholar ↗
  10. Cassandre Coyer, Isha Marathe. 2024. Legal Industry Players Missed a Microsoft AI Loophole That Could Expose Confidential Data. Law.com. https://www.law.com/legaltechnews/2024/03/20/legal-industry-players-missed-a-microsoft-ai-loophole-that-could-expose-confidential-data OpenAlex ↗ · Scholar ↗
  11. John Fields, Kevin Chovanec, Praveen Madiraju. 2024. A Survey of Text Classification With Transformers: How Wide? How Large? How Long? How Accurate? How Expensive? How Safe?. IEEE Access. doi:10.1109/ACCESS.2024.3349952. OpenAlex ↗ · Scholar ↗
  12. Pengcheng He, Jianfeng Gao, Weizhu Chen. 2021. DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing. CoRR. https://arxiv.org/abs/2111.09543 our card
  13. Raghavendra Pappagari, Piotr Zelasko, Jesús Villalba, Yishay Carmiel, Najim Dehak. 2019. Hierarchical Transformers for Long Document Classification. 2019 IEEE Automatic Speech Recognition and Understanding Workshop (ASRU). doi:10.1109/ASRU46091.2019.9003958. OpenAlex ↗ · Scholar ↗
  14. Ming Ding, Chang Zhou, Hongxia Yang, Jie Tang. 2020. CogLTX: Applying BERT to Long Texts. Advances in Neural Information Processing Systems. https://proceedings.neurips.cc/paper_files/paper/2020/file/96671501524948bc3937b4b30d0e57b9-Paper.pdf OpenAlex ↗ · Scholar ↗
  15. Hyunji Park, Yogarshi Vyas, Kashif Shah. 2022. Efficient Classification of Long Documents Using Transformers. Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers). doi:10.18653/v1/2022.acl-short.79. OpenAlex ↗ · Scholar ↗
  16. Rada Mihalcea, Paul Tarau. 2004. TextRank: Bringing Order into Text. Proceedings of the 2004 Conference on Empirical Methods in Natural Language Processing. https://aclanthology.org/W04-3252/ OpenAlex ↗ · Scholar ↗
  17. Iz Beltagy, Matthew E. Peters, Arman Cohan. 2020. Longformer: The Long-Document Transformer. https://arxiv.org/abs/2004.05150 our card
  18. Ilias Chalkidis, Emmanouil Fergadiotis, Prodromos Malakasiotis, Ion Androutsopoulos. 2019. Large-Scale Multi-Label Text Classification on EU Legislation. Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics. doi:10.18653/v1/P19-1636. our card
  19. Quoc Le, Tomas Mikolov. 2014. Distributed Representations of Sentences and Documents. Proceedings of the 31st International Conference on Machine Learning. https://proceedings.mlr.press/v32/le14.html our card
  20. James Mullenbach, Sarah Wiegreffe, Jon Duke, Jimeng Sun, Jacob Eisenstein. 2018. Explainable Prediction of Medical Codes from Clinical Text. Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers). doi:10.18653/v1/N18-1100. our card
  21. Lulu Wan, George Papageorgiou, Michael Seddon, Mirko Bernardoni. 2019. Long-length Legal Document Classification. https://arxiv.org/abs/1912.06905 OpenAlex ↗ · Scholar ↗
  22. Purbid Bambroo, Aditi Awasthi. 2021. LegalDB: Long DistilBERT for Legal Document Classification. 2021 International Conference on Advances in Electrical, Computing, Communication and Sustainable Technologies (ICAECT). doi:10.1109/ICAECT49130.2021.9392558. OpenAlex ↗ · Scholar ↗
  23. Chaojun Xiao, Xueyu Hu, Zhiyuan Liu, Cunchao Tu, Maosong Sun. 2021. Lawformer: A pre-trained language model for Chinese legal long documents. AI Open. doi:https://doi.org/10.1016/j.aiopen.2021.06.003. our card
  24. Victor Sanh, Lysandre Debut, Julien Chaumond, Thomas Wolf. 2020. DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter. arXiv:1910.01108. https://arxiv.org/abs/1910.01108 our card
  25. Yiming Cui, Wanxiang Che, Ting Liu, Bing Qin, Ziqing Yang. 2021. Pre-Training With Whole Word Masking for Chinese BERT. IEEE/ACM Transactions on Audio, Speech, and Language Processing. doi:10.1109/TASLP.2021.3124365. our card
  26. Dimitris Mamakas, Petros Tsotsi, Ion Androutsopoulos, Ilias Chalkidis. 2022. Processing Long Legal Documents with Pre-trained Transformers: Modding LegalBERT and Longformer. Proceedings of the Natural Legal Language Processing Workshop 2022. doi:10.18653/v1/2022.nllp-1.11. OpenAlex ↗ · Scholar ↗
  27. Qiqi Wang, Kaiqi Zhao, Robert Amor, Benjamin Liu, Ruofan Wang. 2022. D2GCLF: Document-to-Graph Classifier for Legal Document Classification. Findings of the Association for Computational Linguistics: NAACL 2022. doi:10.18653/v1/2022.findings-naacl.170. OpenAlex ↗ · Scholar ↗
  28. Zehua Li, Neel Guha, Julian Nyarko. 2023. Don't Use a Cannon to Kill a Fly: An Efficient Cascading Pipeline for Long Documents. Proceedings of the Nineteenth International Conference on Artificial Intelligence and Law. doi:10.1145/3594536.3595142. OpenAlex ↗ · Scholar ↗
  29. Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov. 2019. RoBERTa: A Robustly Optimized BERT Pretraining Approach. doi:10.48550/ARXIV.1907.11692. our card