<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alec Stashevsky on Medium]]></title>
        <description><![CDATA[Stories by Alec Stashevsky on Medium]]></description>
        <link>https://medium.com/@AlecStashevsky?source=rss-de9be4b48762------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CVtUbKoHr-Q39dmRoLTv8w.jpeg</url>
            <title>Stories by Alec Stashevsky on Medium</title>
            <link>https://medium.com/@AlecStashevsky?source=rss-de9be4b48762------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:39:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AlecStashevsky/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimizing Sentence Transformers for Entity Resolution]]></title>
            <link>https://techblog.fetch.com/optimizing-sentence-transformers-for-entity-resolution-fb07be78e5e5?source=rss-de9be4b48762------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb07be78e5e5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[entity-resolution]]></category>
            <category><![CDATA[fetch-rewards]]></category>
            <category><![CDATA[sentence-transformers]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Alec Stashevsky]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 16:25:04 GMT</pubDate>
            <atom:updated>2025-12-11T22:27:01.471Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://alecstashevsky.com/">Alec Stashevsky</a>, <a href="https://www.linkedin.com/in/melanie-riley/">Melanie Riley</a>, <a href="https://www.linkedin.com/in/petecampb/"><strong>Peter Campbell</strong></a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wPVRp9ZYrZOP0oZqf_lgg.png" /><figcaption>Embedding space of retailer names produced by a custom sentence transformer for entity resolution at Fetch</figcaption></figure><p>At Fetch, we reward our users for snapping pictures of their receipts. Each day, this happens over 10 million times.¹ Our machine learning and engineering teams are hard at work building systems that extract, normalize, and enrich information from these receipts as accurately and quickly as possible.</p><p>One of the most important steps in this pipeline is entity resolution. <em>Entity resolution</em> is the process of identifying and linking records that correspond to the same entity across different data sources. Paper receipts have diverse conventions for representing important information such as the originating business or retailer, purchased product descriptions, and payment information.</p><p>It is not enough to “read” the information as it appears on the receipt. We need to understand the context of the information and link it to some known “platonic form”<em>.</em> We often refer to this as the <em>canonical entity.</em> Canonical entities are the representations used by our internal systems and reporting teams business-wide.</p><p>For example, consider the generic fast food business “Fast Food Place.” This retailer may be printed in many different ways on a paper receipt:</p><ul><li>“Fast Food Place Downtown”</li><li>“Fast Food Place Express”</li><li>“Fast Food Place Santa Anita Mall”</li><li>“Fast Food Store #123”</li><li>“DeliveryService — Fast Food Place”</li><li>“Thanks for shopping at Fast Food Place!”</li></ul><p>The same product can also be printed in many different ways:</p><ul><li>“Soda Brand Cola 12CT”</li><li>“SodaBrand Cola Dozen Pack”</li><li>“SB Cola 12x12oz”</li></ul><p>If our product catalogue uses the canonical name Soda Brand 12 Pack, then we need to be able to understand that all of these different representations refer to that same canonical product entity.</p><p>This is a difficult problem for a variety of reasons. It requires Fetch to have an opinionated catalogue of retailers, products, and any other entity we want to understand across diverse contexts. This diversity is exacerbated by errors propagated from upstream information extraction systems, such as OCR, which expand the space of lexical variants — a problem that requires scalable and generalized understanding to solve.</p><h3>Our Approach</h3><p>We apply a variety of machine learning and <a href="https://en.wikipedia.org/wiki/Information_retrieval">information retrieval</a> methods to solve this task. One of the most important methods is the <em>sentence transformer.</em> Sentence transformers are a type of deep neural network that take in a sequence of text and output a dense vector representation of that text sequence. This vector representation or <em>embedding</em> is tuned to capture the semantic meaning of the text such that similar entities will be positioned closer together and dissimilar entities will be farther apart. We then exploit the properties of <em>vector spaces</em> to quickly understand and compare semantic relationships between many different text sequences and retrieve the most relevant ones. We call this <em>dense retrieval</em>.</p><p>The paradigm of embedding and dense retrieval has been popularized in a variety of natural language understanding tasks, particularly <a href="https://huggingface.co/tasks/question-answering">question answering</a>, document retrieval, and <a href="https://en.wikipedia.org/wiki/Semantic_search">semantic search</a>. We have found that it is also effective in entity resolution in retail and e-commerce. While search and information retrieval are concerned with finding a <em>set</em> of relevant results based on some query, entity resolution is concerned with matching the query to <em>a single entity</em> in a catalogue of known entities.</p><p>We experimented with several popular sentence transformer architectures including <a href="https://arxiv.org/abs/2004.09297">MPNet</a>, <a href="https://huggingface.co/sentence-transformers/paraphrase-MiniLM-L12-v2">paraphrase-MiniLM</a>, and <a href="https://huggingface.co/BAAI/bge-small-en-v1.5">bge-small-en-v1.5.</a> The first model we trained was an MPNet model; However, we later realized a lack of support for optimized inference runtimes and particularly within the Hugging Face <a href="https://huggingface.co/docs/optimum/index">Optimum</a> library would make it a hard sell for deployment. We quickly pivoted to smaller models with more support before eventually landing on the recent bge-small-en-v1.5.</p><p>We would later realize that a few blog posts on optimizing the new <a href="https://arxiv.org/pdf/2309.07597.pdf">BGE</a> models should not be taken as a sign that it would be easy. Hence, we are writing this blog post to share our tips and tricks for optimizing sentence transformers for entity resolution.</p><h4>Domain Adaptation</h4><p>Most sentence transformers are pretrained on large corpora of natural language, such as Wikipedia, news articles, or books. We have found that these embeddings are not always effective for our domain-specific entity resolution tasks.</p><p>The language on receipts is anything but “natural.” Receipts are a type of <em>visually-rich</em> document where much of the underlying semantics are communicated through visual characteristics like the layout, alignment, typography, or size of text, rather than the text itself. By leveraging these other modalities receipts are able to optimize the amount of information conveyed against print space. This also means text is often abbreviated and supplemented with symbology under loose conventions. Learning robust representations of these conventions is key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5o1Mkd8_2mXNN27e6y9ag.png" /><figcaption>Examples of the visually-induced semantics on receipts.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUWPiOuxK0dbuhWvm0OzLg.png" /><figcaption>Diversity in format conventions and semantic linkage structure</figcaption></figure><p>To solve this problem, we explored a variety of domain adaptation techniques. For retailer names, we fine-tuned the sentence transformer on a corpus of raw retailer names and their assigned canonical name using a <a href="https://arxiv.org/abs/1705.00652">Multiple Negatives Ranking (MNR)</a> objective.² We found that this significantly improved the quality of the embeddings for our entity resolution tasks.</p><p>The embedding spaces produced by the models before and after fine-tuning are pictured below. We use the <a href="https://jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf">t-SNE</a> algorithm to project the 384-dimension embedding vectors into 3-dimensional space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0L_Scgknvsr7H9SyY3X2pA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6pximo7bkQs0caqnaZt5w.png" /></figure><p>The retailer name clusters are much more robust when produced by the trained model. This is because the semantics of retailer name variants, abbreviation conventions, and OCR mistakes are learned primarily through domain adaptation. Traditional semantic search corpora like those on the <a href="https://huggingface.co/blog/mteb">Massive Text Embedding Benchmark</a> skew towards prose and natural language, but still transfer crucial knowledge.</p><p>In other cases which differ much more from natural prose, such as product descriptions, we explored <a href="https://arxiv.org/abs/2004.10964">domain adaptive pretraining</a> in addition to fine-tuning.</p><h4>Training Framework</h4><p>Our machine learning teams use a variety of frameworks to fine-tune and pretrain models, with <a href="https://lightning.ai/docs/pytorch/stable/">PyTorch Lightning</a> and Hugging Face <a href="https://huggingface.co/docs/transformers/en/index">Transformers</a> being the most popular. However, we found that the <a href="https://www.sbert.net/">SentenceTransformers</a> library was particularly effective for high-throughput experimentation with popular models and training objectives as it allowed us to leverage complex loss functions easily. That being said, the lack of support for distributed training and experiment tracking are significant drawbacks. We recommend James Briggs’ <a href="https://www.pinecone.io/learn/series/nlp/"><em>Natural Language Processing for Semantic Search</em></a> as an excellent resource on the trade-offs between high-level libraries like SentenceTransformers and base PyTorch implementations.</p><h4>Data Augmentation</h4><p>One of the largest problems with embedding text extracted from receipt images is the presence of OCR errors and specific conventions not present in natural language. We augmented our fine-tuning corpus to extend its effective size and diversity of examples. We found two augmentation strategies to be particularly effective in improving the quality and robustness of the embeddings:</p><ol><li>OCR Noise Simulation</li><li>Strategic Example Mining</li></ol><p>OCR errors are generally characterized by the introduction of noise into the extracted text. Simulating OCR errors in the training data improved the robustness of the embeddings to these errors. To simulate OCR-based noise, we introduce random character deletion, insertion, and substitution. We also make use of a predefined mapping of character substitutions based on the error profile our OCR system.</p><p>Strategic example mining allows us to exploit patterns found during error analysis and inject them into training. A prime instance involves delivery service providers. The delivery provider’s name often precedes the retailer, <em>e.g. </em>“DELIVERY SERVICE — Fast Food Place.” Injecting common delivery provider names as hard positive examples reduced the semantic impact of such conventions. Conversely, for hard negatives, we tackle confusion around large retailers with distinct fuel brands by adding qualifiers like “fuel” or “gas station” to certain retailer names.</p><p>We can also inject hard examples by exploiting lexical similarity or mining the embedding space for the most difficult examples which lie close to a decision boundary. This is an nascent area of research but a useful application of <em>active learning</em> which is ongoing across multiple ML projects at Fetch.</p><p>The essence of our approach lies in fine-tuning the model’s sensitivity to minor lexical shifts that carry significant semantic weight, such as distinguishing between “Jethro’s Bar” and “Jethro’s BBQ,” while ensuring resilience against OCR-induced errors like “Jethro’s BBO.” Achieving this delicate balance, especially with short retailer names, is crucial. Modeling such complex semantic relationships is a big reason why we opted for a sentence transformer.</p><h4>Evaluation</h4><p>The nature of the entity resolution task is such that we really only care about the top-most result for a given query. However, there are many entities that just aren’t present in our catalogue. In such cases we want the model to acknowledge this through a lack of “confidence.”</p><p>To address this we apply a binarizer by thresholding the similarity (or model) scores rather than always taking the top-1 prediction. In this way, the problem is reduced to binary classification where we consider the following positive and negative cases:</p><p><strong>True Positive:</strong></p><ol><li>Canonical entity is present in the catalogue</li><li>Top-1 prediction is the correct canonical entity</li><li>Similarity score is <em>above</em> some threshold</li></ol><p><strong>True Negative:</strong></p><ol><li>Canonical entity is not present in the catalogue</li><li>Top-1 prediction similarity score is <em>below</em> some threshold</li></ol><p>For this use-case we focused on precision and low false positive rate at the top-most ranking. These metrics are commonly denoted by precision@1 and fpr@1, respectively.</p><h3>Deployment</h3><p>The Fetch Machine Learning team is responsible for both R+D and deployment. ML team members use production requirements to inform development from the very beginning and across the lifecycle of the project. Retailer entity resolution is a critical step in rewarding users instantly for snapping pictures of their receipts. Low-latency online inference is critical.</p><p>We thought it would be easy to optimize our embedding model for latency using <a href="https://onnxruntime.ai/">ONNX Runtime</a>, a popular framework for accelerated machine learning. We were wrong. If it was easy, we wouldn’t be writing this blog post — but our hope is to make that easier for the next person!</p><h4>Model Optimization</h4><p>Models trained using SentenceTransformers are not optimized out-of-the-box. We had to make a number of optimizations to the model and serving engine to make it suitable for our production workloads. This included limiting the size of our semantic space, exploiting approximate nearest neighbors algorithms for efficient dense retrieval, and optimizing the serving engine for low-overhead inference.</p><p>Preparing our sentence transformer for ONNX Runtime involved a few key steps:</p><h4>Graph Optimization</h4><p>Graph optimization refers to optimizing the low-level execution of operations defined by a model’s computation graph. These are generally highly specialized for different hardware accelerators, <em>e.g. </em>CUDA-capable GPUs, TPUs, etc. Looking across the entire computation graph allows us to eliminate, fuse, or simplify low-level operations.</p><p>To apply these graph optimizations, we use <a href="https://huggingface.co/docs/optimum/index">Optimum</a> which provides a convenient wrapper over ONNX Runtime with several <a href="https://huggingface.co/docs/optimum/onnxruntime/usage_guides/optimization#optimizing-a-model-during-the-onnx-export">optimization levels</a> designed to provide reasonable defaults for transformer-based architectures. These include <a href="https://onnxruntime.ai/docs/performance/model-optimizations/float16.html#mixed-precision">mixed-precision</a> inference, <a href="https://onnxruntime.ai/docs/performance/model-optimizations/graph-optimizations.html#extended-graph-optimizations">kernel fusion</a>, and efficient GELU approximation.</p><h4>Environment Alignment</h4><p>ONNX Runtime can perform optimizations in an offline fashion by serializing the optimized artifacts to disk. This is a nice feature because performing these optimizations can take a significant amount of time especially for complex optimizations or model architectures. Serializating pre-compiled artifacts allows us to optimize the model once, ahead of inference time, then quickly load it into the production environment.</p><p>When performing offline optimizations, its critical to replicate the production runtime exactly, as these optimizations are highly specialized. In practice, this means spinning up a compute node with the same hardware, CUDA drivers, and python runtime as our deployment environment. We use <a href="https://aws.amazon.com/machine-learning/amis/">AWS Deep Learning AMIs</a> to handle management of CUDA dependencies as simply using the wrong CUDA version can lead to a model that is not compatible or degrades in the production environment.</p><p>Using the default O4 optimization level with the Optimum-CLI, we found that the default settings triggered warnings. Optimum automatically tests for discrepancies in the outputs between the compiled and native model artifacts; However, the inputs are generated randomly and due to this <a href="https://github.com/microsoft/onnxruntime/issues/18945">issue</a> for right-padded models in particular, we advise that users always test for accuracy degradation on <strong>their own real data</strong>. We also found setting a custom optimization configuration using OptimizationConfig and in particular setting disable_attention_fusion=True was necessary to maintain accuracy with the uncompiled BGE architecture. The exact configuration we used is below:</p><pre>from optimum.onnxruntime import (<br>    ORTOptimizer, <br>    OptimizationConfig,<br>)<br><br># Optimize graph<br>optimization_config = OptimizationConfig(<br>    optimization_level=2,<br>    optimize_for_gpu=True,<br>    fp16=True, # mixed precision<br>    enable_transformers_specific_optimizations=True,<br>    disable_gelu_fusion=False,<br>    disable_layer_norm_fusion=False,<br>    disable_attention_fusion=True, # required for BGE model<br>    disable_skip_layer_norm_fusion=False,<br>    disable_bias_skip_layer_norm_fusion=False,<br>    disable_bias_gelu_fusion=False,<br>    disable_embed_layer_norm_fusion=False,<br>    enable_gelu_approximation=True,<br>    use_mask_index=False,<br>    no_attention_mask=False,<br>    disable_shape_inference=False,<br>    use_multi_head_attention=True,<br>    enable_gemm_fast_gelu_fusion=False,<br>    use_raw_attention_mask=True,<br>    disable_rotary_embeddings=False,<br>)<br><br>optimizer = ORTOptimizer.from_pretrained(&quot;BAAI/bge-small-en-v1.5&quot;)<br>optimizer.optimize(save_dir=&quot;bge_onnx_opt&quot;, optimization_config=optimization_config)</pre><p>Once you’ve got your compiled artifact, you can test it by loading the model via the ORTModel class — but what&#39;s more fun is loading it into <a href="https://github.com/lutzroeder/Netron">Netron</a> to visualize the full computation graph! After all, <em>interoperability</em> is what ONNX is all about!</p><p>Below is a screen shot of the BGE model’s architecture visualized using the hosted Netron <a href="https://netron.app/">app</a>. The full model graph is hilariously large, but we can see the main components of the model properties including the token_embeddings and sentence_embedding outputs on the right panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vmQiEWE929QhGIs-" /><figcaption>Computation graph for the BGE model architecture in ONNX format visualized via Netron.</figcaption></figure><p>Visualizing the model properties is enlightening. We can see the model was compiled to support dynamic inputs, so the input tensor dimensions may vary based on the batch_size and sequence_length passed to the model during inference. This is beneficial for our use-case where the length and number of instances of retailer names differs across requests. Optimum exports for dynamic axes by default, but if your use-case takes a fixed input shape you can specify this when exporting your model. You can often reap even more speed-ups by compiling the model for a fixed input size.</p><h4>Custom Inference Handling</h4><p>At the time of writing, Optimum has 12 different wrappers for downstream <a href="https://huggingface.co/docs/optimum/en/onnxruntime/usage_guides/pipelines">tasks</a>. The feature-extraction task is designed for generic embedding generation, but it expects last_hidden_state in the model output. This is not output by most sentence transformers, which, per the model properties in the Netron graph, shows the outputs as token_embeddings and sentence_embedding. This created an issue when using the ORTModelForFeatureExtraction wrapper, so we ended up having to define a custom <a href="https://huggingface.co/docs/transformers/add_new_pipeline">Pipeline</a> to support the output schema:</p><pre>import torch.nn.functional as F<br>from transformers import Pipeline<br><br>class SentenceEmbeddingPipeline(Pipeline):<br>    def _sanitize_parameters(self, **kwargs):<br>        # we don&#39;t have any hyperparameters to sanitize<br>        preprocess_kwargs = {}<br>        return preprocess_kwargs, {}, {}<br><br>    def preprocess(self, inputs):<br>        return self.tokenizer(inputs, padding=True, truncation=True, return_tensors=&quot;pt&quot;)<br>    <br>    def _forward(self, model_inputs):<br>        output = self.model(**model_inputs)<br>        return output<br><br>    def postprocess(self, model_outputs):<br>        # Perform pooling<br>        embeddings = self.cls_pooling(model_outputs)<br>        # Normalize embeddings<br>        embeddings = F.normalize(embeddings, p=2, dim=1)<br>        embeddings = embeddings.numpy().flatten()<br>        return embeddings<br><br>    def cls_pooling(self, model_output):<br>        return model_output[0][:, 0]</pre><p>The SentenceEmbeddingPipeline makes use of CLS Pooling to extract the sentence embedding. If you are using a different model, make sure to replace cls_pooling with the appropriate pooling function.³</p><p>Finally, we wrap the ONNX model and custom embedding generation pipeline to form the top-level inference API.</p><pre>from typing import List<br>from transformers import AutoTokenizer<br>from optimum.onnxruntime import ORTModelForCustomTasks<br>from pipeline import SentenceEmbeddingPipeline<br><br>class ONNXEmbeddingGenerator:<br>    def __init__(self, model_dir, device):<br>        self.model = ORTModelForCustomTasks.from_pretrained(<br>            model_dir,<br>            use_io_binding=True,<br>            file_name=&quot;model_optimized.onnx&quot;<br>        )<br>        self.tokenizer = AutoTokenizer.from_pretrained(model_dir)<br>        self.pipeline = SentenceEmbeddingPipeline(model=self.model, tokenizer=self.tokenizer, device=self.device)<br>    <br>    def generate_embeddings(self, inputs: List[str]):<br>        return self.pipeline(inputs, batch_size=len(inputs))</pre><p>This was a far cry from the one line of CLI code we were hoping for, but the benefits of the optimized runtime soon became clear.</p><h4>Benchmarking ONNX Runtime</h4><p>We benchmarked our inference performance using the <a href="https://github.com/huggingface/optimum-benchmark/tree/main">Optimum Benchmark</a> library from Hugging Face. The latency benchmark was run with a fixed batch size of 1, and the throughput benchmark was run with a sequence length of 32. Both benchmarks were run on a single NVIDIA A10G Tensor Core GPU. The benchmarks comparing the optimized ONNX model vs PyTorch are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*3XuKHCwF3j9Xc6bM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*k3kwEPT2WRgWIG6P" /><figcaption>Output visualization from the Hugging Face optimum-benchmark library for the bge-small-en-v1.5 model.</figcaption></figure><p>With the accelerated runtime, we were able to achieve close to a 3x speedup and a significant increase in throughput over PyTorch eager mode.</p><h4>Dense Retrieval Optimization</h4><p>The crux of semantic search and dense retrieval is the ability to quickly find the most similar embeddings given some query. This makes efficient retrieval, generally through approximate nearest neighbor (ANN) algorithms, a critical part of the pipeline.</p><p>The cardinality of retailer catalogue is quite small compared to most search use-cases (thousands rather than millions or billions). We found that even using a brute-force search was fairly efficient compared to embedding generation. Nonetheless, we shaved off a bit of compute by leveraging <a href="https://ieeexplore.ieee.org/abstract/document/8594636">hierarchical navigable small worlds</a> to index our embeddings.⁴ We found the ANN algorithm did not degrade our evaluation metrics compared to brute force search.</p><h4>Model Server Optimization</h4><p>We serve our model using <a href="https://pytorch.org/serve/">TorchServe</a>. In addition to model-specific optimizations we also tuned a few serving hyperparameters, the most important of which is the number of TorchServe <a href="https://pytorch.org/serve/internals.html?highlight=backend+workers">workers</a>. We found 2 workers to produce optimal results against the throughput/latency tradeoff.</p><h3>Load Testing</h3><p>We use <a href="https://locust.io/">Locust</a> to load test all our ML services. Our load test results under the optimized configuration are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zKrqk-bUQdrROceq" /><figcaption>Locust telemetry under increasing load. As the pressure of inference requests increases, throughput (Requests per Second) stabilizes and latency (Response Times) begins to rise. This indicates we are backing up TorchServe worker queues and sufficiently straining the service.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*Q7eBHaOlxiq02HvGkKlqMg.png" /><figcaption>Topline statistics for the load test shows a max throughput of 259 RPS and 29 ms latency at the 99th percentile.</figcaption></figure><p>We were able to achieve a maximum throughput of almost 260 RPS. Increasing concurrent requests beyond 260 RPS resulted in increased latency and began backing up worker queues. This gives us a baseline to craft horizontal scaling policies.</p><h4>Shadow Pipeline</h4><p>To capture the true flora and fauna of our production environment, we make use of a shadow-pipeline which siphons data from production to simulate real-world traffic patterns otherwise hard to mimic. We monitor key telemetry around the service health and model output, including the distribution of model scores and top-1 predictions. This is a critical part of our deployment process, as it allows us to catch issues before they reach production.</p><h4>Tracing</h4><p>To help us identify bottlenecks and further optimize the service, we implement <a href="https://opentelemetry.io/">OpenTelemery</a> tracing for core functions in our entity resolution service:</p><ol><li>Pre/Post-Processing (<em>e.g. </em>Tokenization)</li><li>Embedding Generation</li><li>Dense Retrieval</li></ol><p>These traces are surfaced to our internal <a href="https://www.jaegertracing.io/">Jaeger</a> instance used across our engineering organization.</p><p>We were especially interested in monitoring these traces under load because we chose to run both the embedding model and ANN algorithm on the same compute node. This is perhaps a less-common approach as it demands extremely heterogeneous compute from a single resource.</p><p>Tracing allowed us to pinpoint compute bottlenecks under varying load patterns, but also ensure batch size was not confounding the results. Below shows a nominal trace for a request to the service. We were careful to include the batch.size as a tag to understand how dynamic batching can affect the latency of each step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pi3NSi0QKQXBU0My" /><figcaption>Example of a trace for the inference pass within the TorchServe model server. The request took 5.33 ms in total, of which 4.63 ms were used for embedding generation.</figcaption></figure><h3>Monitoring and Observability</h3><p>Our services emit metrics to a <a href="https://www.hostedgraphite.com/">Hosted Graphite</a> instance which powers our internal <a href="https://grafana.com/">Grafana</a> observability stack. We use Grafana to visualize key metrics, alert on anomalies, measure drift, and monitor the overall performance of our ML services.</p><p>For the retailer entity resolution model, we monitor the distribution of both model scores and top-1 predictions. We can also monitor how our hit-rate changes in response to the similarity threshold set for acceptance. These metrics roll up to our core production ML Monitor, a dashboard that provides a high-level overview of the health of all our models in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHFuz8or1KkoCcAbzOcvHA.png" /><figcaption>The distribution of cosine similarity scores returned by the retailer entity resolution model over a 7 day period. The distribution is highly left-skewed with over half of the responses greater than 98% similar.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fnz0YetepoLNozfElxVgEA.png" /><figcaption>The percentage of “hits” over a 7-day period. A hit implies a successful response with a cosine similarity score over some predefined threshold.</figcaption></figure><h4>What’s Next?</h4><p>Much work remains. On the modeling front, we want to explore joint embedding of retailers and products (a somewhat distorted form of <em>query expansion</em>) and more advanced active learning like hard negative mining of latent space.</p><p>On the Infra front, we are exploring the use of dedicated vector databases, and separating out the compute workload for more fine-grained control over scaling.</p><p>On the Ops front, we want to move towards more robust search index management solutions that support automatic updates. We also plan to expand the depth of our production monitoring to pinpoint specific retailers and business verticals where our search index is sparse and resolution capabilities lacking. This will also feed into <a href="https://hai.stanford.edu/news/humans-loop-design-interactive-ai-systems">human-in-the-loop</a> systems to continually build our understanding over retail and e-commerce.</p><p>[1]: <em>See </em><a href="https://business.fetch.com/trends-and-insights/why-americas-most-iconic-brands-are-moving-to-fetch">https://business.fetch.com/trends-and-insights/why-americas-most-iconic-brands-are-moving-to-fetch</a>.</p><p>[2]: Raw retailer names refers to text that is extracted directly from paper receipt images. In some cases there may be multiple instances of retailer text on the receipt. We treat each of these as independent(anchor, positive)pairs during training.</p><p>[3]: An alternative is to use the sentence_embedding output, but we found minor differences in the outputs, so chose to index the [CLS] token embedding directly.</p><p>[4]: This was originally implemented using FAISS on the same compute node as the model, but there is much work left to be done here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb07be78e5e5" width="1" height="1" alt=""><hr><p><a href="https://techblog.fetch.com/optimizing-sentence-transformers-for-entity-resolution-fb07be78e5e5">Optimizing Sentence Transformers for Entity Resolution</a> was originally published in <a href="https://techblog.fetch.com/">Fetch Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer Hydranets and Multi-Task Learning with Hugging Face and PyTorch: Ensembling vs.]]></title>
            <link>https://medium.com/@AlecStashevsky/transformer-hydranets-and-multi-task-learning-with-hugging-face-and-pytorch-ensembling-vs-48687502a38a?source=rss-de9be4b48762------2</link>
            <guid isPermaLink="false">https://medium.com/p/48687502a38a</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Alec Stashevsky]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 00:00:36 GMT</pubDate>
            <atom:updated>2024-03-17T20:32:26.895Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformer Hydranets and Multi-Task Learning with Hugging Face and PyTorch: Ensembling vs. Entwinement | Alec Stashevsky</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRT02PK3WuSiM90N1NRTog.png" /><figcaption><em>Water Jar with Herakles and Iolaos Attacking the Hydra (Alternate Title).</em> 520–510 B.C.<br>Digital image courtesy of Getty’s Open Content Program.</figcaption></figure><p><em>The Lernaean Hydra, a many-headed serpentine water monster, has been living with us for over 2,700 years. Heracles is said to have used the Hydra’s poisonous blood to dip arrows later used to kill the centaur Nessus. Today the Hydra-reified in many forms-continues to augment our tools in the hunt for artificial intelligence.</em></p><p>Production machine learning systems require teams of expert problem-solvers, each with a unique skill set, collaborating closely together to maintain and improve performance. Each member contributes their expertise, and their combined effort leads to a solution greater than what any individual could achieve alone. In what can perhaps be characterized as a fit of introspection, distilling the essence of this expert collaboration into the ML systems themselves has been undergoing a radical transformation. This is the world of ensemble machine learning.</p><p>It is <a href="https://pub.towardsai.net/gpt-4-8-models-in-one-the-secret-is-out-e3d16fd1eee0">believed</a> that a specific form of ensemble learning- <a href="https://deepgram.com/learn/mixture-of-experts-ml-model-guide">Mixture of Experts</a>-is behind one of the most powerful closed-sourced LLMs available today. However, unlike the well-coordinated teams of engineers who build these systems, <a href="https://neptune.ai/blog/ensemble-learning-guide">traditional ensemble systems</a> didn’t have direct ways to learn from or grow alongside each other. Instead they leveraged the power of <a href="https://medium.com/inspiredbrilliance/object-detection-through-ensemble-of-models-fed015bc1ee0">consensus</a> and aggregation. Knowledge transfer is an essential part of building successful ML teams, but the models in an ensemble share little information between each other and are agnostic to how their predictions are used downstream.</p><p>Welcome to a series of blog posts that is not about ensemble learning. Instead, this series focuses on a less well-known modeling paradigm that seeks to exploit, rather than ignore, collaboration. This is the paradigm of <em>multi-task learning</em> (MTL). I find <a href="https://www.ruder.io/about/">Sebasatian Ruder’s</a> MTL definition particularly practical:</p><blockquote><em>MTL comes in many guises: joint learning, learning to learn, and learning with auxiliary tasks are only some names that have been used to refer to it. Generally, as soon as you find yourself optimizing more than one loss function, you are effectively doing multi-task learning</em></blockquote><p>MTL’s strength lies in exploiting heightened signal in data. Rather than building ensembles from diverse models, MTL <em>learns diversely</em> by entwining multiple objectives. This creates biases that can build robust and versatile representation power.</p><p>Multi-task models can be endowed with many task-specific <em>heads</em> that can share outputs and influence over the core model backbone, and even each other. We refer to these multi-headed models as <em>hydranets</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*7yyUYEYi94U6-mbQ.png" /></figure><p>I’ve struggled to find good resources on building hydranets and training them. In general it is more complex and less talked about-perhaps due to its many “guises”. Naturally, I find it a more intriguing paradigm. This is why I’ve decided to author this series.</p><h3>The Power of Multi-Task Learning</h3><p>Multi-task learning mirrors human learning. Knowledge from one task aids in mastering others. Just as a child uses facial recognition skills to identify other objects, MTL applies learned insights across various tasks. In a more theoretical view MTL is a form of inductive transfer which entices models to favor hypotheses that explain multiple tasks, leading to better generalization. Here are a few perspectives summarized from Ruder (<a href="https://alecstashevsky.com/post/transformer-hydranets-and-multi-task-learning-with-hugging-face-and-pytorch-ensembling-vs.-entwinement/#ref-ruder2017overview">2017</a>).</p><h4>Implicit Data Augmentation</h4><p>Learning from multiple tasks effectively increases training data, or rather the amount of signal that can be gleaned from each data point. Cross-pollination of knowledge can reduce the amount of data needed for each individual task because the model can generalize information from related tasks, making MTL particularly advantageous in scenarios with limited data.</p><h4>Attention Focusing</h4><p>Joint optimization can help the model discern relevant features from a broader viewpoint, reducing spurious pattern recognition that can lead to overfitting. This is especially prone in high-dimensional, noisy data scenarios.</p><h4>Eavesdropping</h4><p>One task can “eavesdrop” on another, learning difficult features more easily by finding simpler patterns in other tasks. One task may interact with features in a more complex way or other features may thwart the model’s ability to learn that task. Its possible to overcome this with eavesdropping.</p><h4>Representation Bias</h4><p>MTL encourages models to favor representations that are effective across different tasks, enhancing generalizability.</p><h4>Regularization</h4><p>MTL introduces a regularizing inductive bias which mitigates overfitting and the model’s ability to fit random noise, known as the <a href="https://www.onurtunali.com/ml/2022/05/04/empirical-rademacher-complexity-and-its-implications-to-deep-learning.html">Rademacher complexity</a>. Different features and labels have different noise distributions which can cancel each other out. Learning jointly reduces the influence of single-source noise creating a more generalized representation.</p><h4>Disadvantages</h4><p>MTL systems can be prone to imbalances between tasks and competition for influence over the model backbone parameters can lead to catastrophic forgetting or bottlenecks in the learning process requiring sophisticated techniques in model design, loss function balancing, and training regimen. The flip side of entwining task learning is the lack of modularity — a key property of ensembles. Adding new tasks or models is much harder with hydranets as it becomes entangled with the rest of the system performance. It is possible to isolate tasks and achieve modularity with MTL by careful freezing of weights, but it is nonetheless more challenging.</p><h3>Use-Case for a Transformer Hydranet</h3><p>Hydranets’ true power shines when there is overlapping knowledge that can be exploited between tasks. Lets consider an example of a content moderation solution. Traditional approaches might deploy separate models for different aspects of content moderation-such as sentiment analysis, toxic comment detection, and spam identification. However, a transformer hydranet can be trained to tackle all these tasks concurrently.</p><p>Sharing a common backbone means hydranet models can gain a more holistic understanding of language nuances crucial to discern both context and intent in content. The model can learn to simultaneously identify toxic language, categorize comments, and evaluate sentiment. Cues learned from each of these tasks can help the model succeed at other tasks in turn. In this sense, the overlapping knowledge can be exploited by the hydranet to create synergy during learning and thus more powerful backbones.</p><p>Hydranet models can also reduce compute resources for inference, especially in cases where they replace ensembles or iterate on top of single-task models. Most of the inference workload is spent computing the forward pass of the model backbone. The forward pass of each model head can be computed in parallel and its usually much lighter than the backbone.</p><p><a href="https://towardsdatascience.com/journey-to-the-center-of-multi-label-classification-384c40229bff">Multi-label classification</a> is another great use-case as it has been traditionally solved with ensembles like one-to-rest or target transformations like taking the power set all labels. In the multi-task learning paradigm, multi-label classification can be modeled directly with a hydranet approach. Rather than running multiple models or exploding the number of targets, we build the forward pass of the model to compute in parallel each label set-a much more organic approach. This works well when you have a strict limit on the overlap of classes, but can fail on <em>pick-all-applicable</em> scenarios.</p><h3>Off The Shelf Transformer Heads</h3><p>One of the great features of Hugging Face’s transformers library is the collection of pre-built heads for performing versatile tasks on top of pre-trained base models. When you navigate to a specific model in the library, like <a href="https://huggingface.co/docs/transformers/model_doc/roberta">RoBERTa</a>, you will see a set of various <a href="https://huggingface.co/docs/transformers/main/en/task_summary#natural-language-processing">tasks</a> that the model is capable of performing such as masked language modeling (MLM), token classification, and sequence classification.</p><p>Predefined task-specific models can be pulled down in a single line of code. Here’s how we can easily instantiate RoBERTa for both token and sequence classification tasks:</p><pre>from transformers import RobertaForTokenClassification, RobertaForSequenceClassification <br><br>token_model = RobertaForTokenClassification.from_pretrained(<br>  &#39;roberta-base&#39;, num_labels=5 <br>)<br><br>sequence_model = RobertaForSequenceClassification.from_pretrained(<br>  &#39;roberta-base&#39;, num_labels=3<br>)</pre><p>In this snippet, num_labels is adjusted based on the task requirements, such as the number of entity types in <a href="https://medium.com/mysuperai/what-is-named-entity-recognition-ner-and-how-can-i-use-it-2b68cf6f545d">Named Entity Recognition</a> (NER) or classes in sequence (text) classification tasks like sentiment analysis.</p><p>Under the hood, transformers defines an explicit model architecture for each task, but in a spectacularly modular way.</p><h4>The Forward Pass</h4><p>Let’s take a closer look at how transformers implements task specific heads and learn about how we architect the same base models to do very different things. Here’s a simplified view of the forward pass for token and sequence classification modules:</p><pre>def forward(self, input_ids, attention_mask=None, labels=None):<br>    # Run through the model backbone <br>    outputs = self.roberta(input_ids, attention_mask=attention_mask)<br>    # Access the last hidden states (embeddings from final base model layer)<br>    sequence_output = outputs[0]<br>    # Feed the embeddings to the task-specific head<br>    logits = self.classifier(sequence_output)<br><br>    # Additional processing for loss calculation and output<br>        # ...<br>        <br>    return logits</pre><p>The only difference between the token and sequence classification models is the last few layer(s) in self.classifier.</p><h3>Token Classification</h3><p>Token classification generates embeddings for <em>each</em> token in the input sequence. Each token embedding is then passed to a dense layer to classify the tokens independently. Here’s a look at what the classifier head looks like in the <a href="https://github.com/huggingface/transformers/blob/b074461ef0f54ce37c5239d30ee960ece28d11ec/src/transformers/models/roberta/modeling_roberta.py#L1358">source code</a>:</p><pre>class RobertaForTokenClassification(RobertaPreTrainedModel):<br>    def __init__(self, config):<br>        super().__init__(config)<br>        self.num_labels = config.num_labels<br>        # Model backbone<br>        self.roberta = RobertaModel(config, add_pooling_layer=False)<br>        # Classification head (a simple MLP)<br>        self.classifier = nn.Linear(config.hidden_size, config.num_labels)</pre><h3>Sequence Classification</h3><p>The goal of sequence / text classification is to predict a class for a sequence of text, rather than each token. The key difference is that we need to produce a single embedding which represents the entire sequence. We do this through a process called <em>pooling</em>. There are several popular pooling mechanisms including mean, max, and CLS.</p><p>The off-the-shelf sequence classification head in RobertaForSequenceClassification uses the embedding of a special [CLS] token trained to represent the entire sequence. This special token is usually appended as the first token in a sequence. We then pass it through a dense layer to classify entire sequence. Here is what that looks like in the source code:</p><pre>class RobertaForSequenceClassification(RobertaPreTrainedModel):<br>    def __init__(self, config):<br>        super().__init__(config)<br>        self.num_labels = config.num_labels<br>        # Model backbone<br>        self.roberta = RobertaModel(config, add_pooling_layer=False)<br>        # Classification head ([CLS] pooling + a simple MLP)<br>        self.classifier = RobertaClassificationHead(config)<br><br><br>class RobertaClassificationHead(nn.Module):<br>    &quot;&quot;&quot;Head for sentence-level classification tasks.&quot;&quot;&quot;<br>    def __init__(self, config):<br>        super().__init__()<br>        self.dense = nn.Linear(config.hidden_size, config.hidden_size)<br>        self.out_proj = nn.Linear(config.hidden_size, config.num_labels)<br>    def forward(self, features, **kwargs):<br>        # Take &lt;s&gt; token (equivalent to [CLS] token) <br>        x = features[:, 0, :]<br>        x = self.dense(x)<br>        x = torch.tanh(x)<br>        x = self.out_proj(x)<br>        return x</pre><p>I won’t go into all the differences of RobertaClassificationHead, as it is essentially a very similar module which makes use of dense layers, but I will point out one key difference which takes place <a href="https://github.com/huggingface/transformers/blob/b074461ef0f54ce37c5239d30ee960ece28d11ec/src/transformers/models/roberta/modeling_roberta.py#L1439">here</a>. This is simply selecting the embedding vector only for the [CLS] token before passing it through a fully-connected layer. In this way we only need to classify a single embedding vector as opposed to one for every token.</p><p>These forward pass implementations highlight the modular nature of transformer models. The same RoBERTa backbone efficiently powers diverse NLP tasks with each head leveraging the core model’s understanding of language. Here we begin to grasp the versatility of transformer architectures and the elegance of PyTorch implementation, paving the way for more complex constructs like hydranets.</p><h3>Extractive Question-Answering (Span Classification)</h3><p><a href="https://huggingface.co/learn/nlp-course/chapter7/7?fw=pt">Extractive question-answering</a> with encoder models takes the form of span classification. The span classification head predicts spans of tokens in the sequence input which answer a given question.<a href="https://alecstashevsky.com/post/transformer-hydranets-and-multi-task-learning-with-hugging-face-and-pytorch-ensembling-vs.-entwinement/#fn11">11</a> This is achieved by returning start_logits and end_logits for every token in the sequence (it is common to set config.num_labels = 2 in span classification). The forward pass follows token classification, except with one key difference:</p><pre>class RobertaForQuestionAnswering(RobertaPreTrainedModel):<br>    def __init__(self, config):<br>        super().__init__(config)<br>        self.num_labels = config.num_labels<br>        # Model backbone<br>        self.roberta = RobertaModel(config, add_pooling_layer=False)<br>        # QA head (a simple MLP identical to token classification head)<br>        self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)<br>        <br>    def forward(self, input_ids, attention_mask=None, labels=None):<br>        # Run through the model backbone <br>        outputs = self.roberta(input_ids, attention_mask=attention_mask)<br>        # Access the last hidden states (embeddings from final base model layer)<br>        sequence_output = outputs[0]<br>        # Feed the embeddings to the task-specific head<br>        logits = self.qa_outputs(sequence_output) ## [batch_size, sequence_length, 2]<br>    <br>        ## QA Specific Differences ##<br>        # Split the logits tensor into two tensors along the last dimension.  <br>        start_logits, end_logits = logits.split(1, dim=-1) ## [batch_size, sequence_length, 1], [batch_size, sequence_length, 1]<br>        <br>        # Squeeze along the last dimension <br>        start_logits = start_logits.squeeze(-1).contiguous() ## [batch_size, sequence_length]<br>        end_logits = end_logits.squeeze(-1).contiguous() ## [batch_size, sequence_length]<br>      <br>        return start_logits, end_logits</pre><p>Here we see that for each token two logits are returned. If we look later on in <a href="https://github.com/huggingface/transformers/blob/514de24abfd4416aeba6a6455ad5920f57f3567d/src/transformers/models/roberta/modeling_roberta.py#L1531C1-L1535C1">code</a>, we see that start_logits and end_logits are supervised by two different loss functions—the requirement for multi-task learning!</p><pre>loss_fct = CrossEntropyLoss(ignore_index=ignored_index)<br>start_loss = loss_fct(start_logits, start_positions)<br>end_loss = loss_fct(end_logits, end_positions)<br>total_loss = (start_loss + end_loss) / 2</pre><p>Hiding in plain site, multi-task learning has been available as an off-the-shelf task head all along! This is a simpler architecture which splits the outputs from a single head and supervises them separately rather than using separate heads. The computation graph is the same, but there are some subtle nuances in performance that I won’t go into here.</p><h3>Off With Their (Transformer) Heads!</h3><p>Building a hydranet is one way to force yourself to recognize the beauty of PyTorch <a href="https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html">Autograd</a>. The essential feature of hydranet architectures is that your model’s forward pass returns multiple objects.</p><p>Let’s take our base RoBERTa model and build a hydranet designed for content moderation. We want to be able to:</p><ol><li>Flag harmful comments (harm, not harm)</li><li>Classify type of harm (<em>e.g.</em> spam, hate, promotions)</li></ol><p>Both tasks can be modeled as sequence classification. Let’s start by stealing some code like all good engineers do! I’ll copy the source code for RobertaForSequenceClassification and we will build out the first head to perform binary sequence classification and the second head perform multi-class classification. I&#39;ve renamed a few things and added separate configs as the output dimensions are different between head 1 and 2:</p><pre>class ContentModerationHydraNet(RobertaPreTrainedModel):<br>    def __init__(self, config, harm_flag_config, harm_type_config):<br>        super().__init__(config)<br>        # Model backbone<br>        self.roberta = RobertaModel(config, add_pooling_layer=False)<br>        # Output a single logit for harm confidence<br>        self.harm_flag_classifier = RobertaClassificationHead(harm_flag_config)<br>        # Output 3 logits for spam, hate, promotion classes<br>        self.harm_type_classifier = RobertaClassificationHead(harm_type_config)<br>    <br>    def forward(self, input_ids, attention_mask=None, labels=None):<br>        # Run through the model backbone <br>        outputs = self.roberta(input_ids, attention_mask=attention_mask)<br>        # Access the last hidden states (embeddings from final base model layer)<br>        sequence_output = outputs[0]<br>        # Feed the embeddings to head 1<br>        logits_harm_flag = self.harm_flag_classifier(sequence_output)<br>        # Feed the embeddings to head 2<br>        logits_harm_type = self.harm_type_classifier(sequence_output)<br><br>        # We now return a tuple of output for each head<br>        return logits_harm_flag, logits_harm_type</pre><p>And that its, now we’ve built a transformer hydranet!</p><h3>Advanced Hydranet Architecture</h3><p>Let’s ratchet this up to the next level. To flag harmful comments we certainly need to understand the content of the comment, but we might also want to exploit additional context by using information about the user who makes the comment or the original post the comment is about. However, our current model can only take text as input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*xpBHbl6uDtJibRlS.png" /></figure><p>We can inject additional information into our model in several interesting ways. If we have historical information on this user, it might be something useful for our harm_flag_classifier to learn on. We can leverage the user&#39;s age and amount of comments that have been flagged for harm in the past as an example. To do this, simply concatenate these onto the final embeddings from the model backbone to provide additional signal:</p><pre>class ContentModerationHydraNet(RobertaPreTrainedModel):<br>    def __init__(self, config, harm_flag_config, harm_type_config):<br>        # Same as above<br>    <br>    # Add additional arguments for user-level features<br>    def forward(self, input_ids, age, prev_flags, attention_mask=None, labels=None):<br>        # Run through the model backbone <br>        outputs = self.roberta(input_ids, attention_mask=attention_mask)<br>        # Access the last hidden states (embeddings from final base model layer)<br>        sequence_output = outputs[0]<br>        # Concatenate user-level features for head 1<br>        harm_flag_input = torch.cat((sequence_output, age.view(-1, 1), prev_flags.view(-1, 1)))<br>        # Feed the RoBERTa embeddings + user-level features to head 1<br>        logits_harm_flag = self.harm_flag_classifier(harm_flag_input)<br>        # Feed the RoBERTa embeddings to head 2<br>        logits_harm_type = self.harm_type_classifier(sequence_output)<br><br>        # We now return a tuple with output for each head<br>        return logits_harm_flag, logits_harm_type</pre><p>Now, we are injecting additional features only into one of the model’s heads. That information can be used to better train the classifier but its also possible for it propagate all the way through to the backbone as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*jQhGftYnydzxLF_S.png" /></figure><p>Let’s go one step further-we haven’t touched our harm_type_classifier yet. Since we are already classifying something as harmful or not with the harm_flag_classifier we might want to use that output to augment the harm_type_classifier as well. That means we will want to feed the output of the first head into the second head. It&#39;s also possible to gate the execution of the second-head on the first head. For example, if we don&#39;t flag a comment as harmful, we don&#39;t need to pass it to the harm_type_classifier at all.</p><pre>class ContentModerationHydraNet(RobertaPreTrainedModel):<br>    def __init__(self, config, harm_flag_config, harm_type_config):<br>        # Same as above<br>    <br>    # Add additional arguments for user-level features<br>    def forward(self, input_ids, age, prev_flags, attention_mask=None, labels=None):<br>        # Run through the model backbone <br>        outputs = self.roberta(input_ids, attention_mask=attention_mask)<br>        # Access the last hidden states (embeddings from final base model layer)<br>        sequence_output = outputs[0]<br>        # Concatenate user-level features for head 1<br>        harm_flag_input = torch.cat((sequence_output, age.view(-1, 1), prev_flags.view(-1, 1)))<br>        # Feed the RoBERTa embeddings + user-level features to head 1<br>        logits_harm_flag = self.harm_flag_classifier(harm_flag_input)<br>        # Concatenate head 1 output to head 2&#39;s input<br>        harm_type_input = torch.cat((sequence_output, logits_harm_flag))<br>        # Feed the RoBERTa embeddings to head 2<br>        logits_harm_type = self.harm_type_classifier(harm_type_input)<br><br>        # We now return a tuple with output for each head<br>        return logits_harm_flag, logits_harm_type</pre><p>Now we’ve got some seriously fun computation graphs to wrestle with. But you don’t have to worry to much about that-PyTorch’s Autograd is taking care of propagating gradients across the entire nn.Module behind the scenes! Gradients are not just being passed from head to backbone-each head can now learn jointly alongside each other as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*zWg7J8rTRKcc1doq.png" /></figure><p>If that gets you wondering how we train hydranets, then stay tuned for the next blog post in this series!</p><h3>References</h3><p>Caruana, Rich. 1997. “Multitask Learning.” <em>Machine Learning</em> 28 (1): 41–75. <a href="https://doi.org/10.1023/A:1007379606734">https://doi.org/10.1023/A:1007379606734</a>.</p><p>Grimal, Pierre. 1996. <em>The Dictionary of Classical Mythology</em>. London, England: Blackwell.</p><p>Hesiod. 1966. <em>Theogony</em>. Oxford University Press Academic Monograph Reprints. London, England: Oxford University Press Reprints distributed by Sa.</p><p>Ruder, Sebastian. 2017. “An Overview of Multi-Task Learning in Deep Neural Networks.” <a href="https://arxiv.org/abs/1706.05098">https://arxiv.org/abs/1706.05098</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*jxXSdlrkAkwO3Ss_.jpg" /></figure><p>Anti-lumper nuance hunter. All opinions are my own.</p><p><em>Originally published at </em><a href="https://alecstashevsky.com/post/transformer-hydranets-and-multi-task-learning-with-hugging-face-and-pytorch-ensembling-vs.-entwinement/"><em>https://alecstashevsky.com</em></a><em> on December 3, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48687502a38a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Putting Document AI into Production with AWS Sagemaker | Alec Stashevsky]]></title>
            <link>https://medium.com/@AlecStashevsky/putting-document-ai-into-production-with-aws-sagemaker-alec-stashevsky-951249873ba7?source=rss-de9be4b48762------2</link>
            <guid isPermaLink="false">https://medium.com/p/951249873ba7</guid>
            <dc:creator><![CDATA[Alec Stashevsky]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 00:00:38 GMT</pubDate>
            <atom:updated>2024-03-17T20:40:25.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UWE6EvLlrpx40NSYs2urw.png" /></figure><p>Check out this <a href="https://aws.amazon.com/solutions/case-studies/fetch-case-study/">AWS case study</a> my team did with AWS to showcase how we deployed a real-time industrial-scale document AI system in under a year!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*D5w3nrypjvlq252j.jpg" /></figure><p>Anti-lumper nuance hunter. All opinions are my own.</p><p><em>Originally published at </em><a href="https://alecstashevsky.com/post/putting-document-ai-into-production-with-aws-sagemaker/"><em>https://alecstashevsky.com</em></a><em> on September 25, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951249873ba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On-the-fly Augmentation with PyTorch Geometric and Lightning: What Tutorials Don’t Teach | Alec…]]></title>
            <link>https://medium.com/@AlecStashevsky/on-the-fly-augmentation-with-pytorch-geometric-and-lightning-what-tutorials-dont-teach-alec-3c61b0e09c7c?source=rss-de9be4b48762------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c61b0e09c7c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[graph-machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Alec Stashevsky]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 00:00:06 GMT</pubDate>
            <atom:updated>2024-03-17T20:21:25.671Z</atom:updated>
            <content:encoded><![CDATA[<h3>On-the-fly Augmentation with PyTorch Geometric and Lightning: What Tutorials Don’t Teach | Alec Stashevsky</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xD_-y6E-fXDm19V0i2dXdA.png" /><figcaption>“Symphony of randomness being conducted by an emporhous form.<br>Underwater various types of fish and sea creatures”, Midjourney. June 4, 2023.</figcaption></figure><blockquote>So much of life, it seems to me, is determined by pure randomness.</blockquote><blockquote>- Sidney Poitier</blockquote><p>On-the-fly data augmentation is a practice which applies random noise to data at the time of loading. This allows for a significant increase in the <em>effective size</em> of your dataset, as each piece of data can be randomly transformed every time it’s loaded, providing a potentially unlimited number of variations. As you iterate over your dataset, randomness can be injected in creative ways including executing some, none, or all of a series of augmentation steps at random each with their own stochastic direction and magnitude.</p><h3>A Lonely Melody Beyond Computer Vision</h3><p>Deep Learning curricula treat augmentation as a core component. Tutorials include sections on data augmentation’s ability to mitigate against common challenges such as class imbalance, error propagation, and scarce data, yet little is published outside of computer vision. You’ll quickly find that resources become scarce once you venture outside cropping and rotating images of cats. The reality is, augmentation strategies are not as well-documented for other types of data, like text or graphs. The journey to implementing custom augmentations here can feel like wandering uncharted territory.</p><p>In my case, working with complex machine learning pipelines that chain models together means augmentation can be a daunting but necessary voyage. I did some research on open-source solutions to simulate noise that can be introduced by OCR models and found <a href="https://github.com/makcedward/nlpaug">nlpaug</a> to be initially promising as it was the only one which touted a “pre-defined OCR mapping” that could apply noise conditioned on common OCR mistakes. I was intrigued, so I dug through the source code until I found the highly coveted <a href="https://github.com/makcedward/nlpaug/blob/master/nlpaug/res/char/ocr/en.json">mapping file</a>. Needless to say, I was a bit disappointed. . . but ChatGPT quickly helped me whip up a much more comprehensive mapping that could be easily substituted. If you’re thinking of using this library I would also caution about this <a href="https://github.com/makcedward/nlpaug/issues/313">issue</a>.</p><h3>Harmonizing Graph Augmentation</h3><p>Unlike images or text, graph data requires specialized augmentation techniques. The connectivity of nodes and edges present unique topology that must be maintained during augmentation, or augmented only with careful intention.</p><p><a href="https://pytorch.org/vision/stable/transforms.html">PyTorch</a> provides a powerful and flexible toolkit for data augmentation, primarily through the use of the Transforms class. At its core, a Transform in PyTorch is a function that takes in some data and returns a transformed version of that data. This could be as simple as resizing an image, flipping text characters at random, or moving data to the GPU. Transforms can be chained together and then attached to a PyTorch Dataset class where they are used to modify data each time it is loaded, generally by a PyTorch DataLoader.</p><p><a href="https://pyg.org/">PyTorch Geometric</a> extends this paradigm to graph data with its own Dataset, DataLoader, and Transform classes. Just like with pure PyTorch, <a href="https://pytorch.org/tutorials/beginner/data_loading_tutorial.html#transforms">custom transforms</a> can be defined simply by inheriting from the BaseTransform class and implementing the __call__ and optionally __init__ methods. Transforms can be then be simply attached to your Dataset and will be called as the data is fetched, like so:</p><pre>import torch_geometric.transforms as T <br>from torch_geometric.datasets import TUDataset <br>transform = T.Compose([T.ToUndirected(), T.AddSelfLoops()]) <br>dataset = TUDataset(path, name=&#39;MUTAG&#39;, transform=transform)</pre><p>While this is the recommended method according to both frameworks, there is a more straightforward approach where you call the transform explicitly on data points or batches:</p><pre>transform = T.Compose([T.ToUndirected(), T.AddSelfLoops()]) <br>dataset = TUDataset(path, name=&#39;MUTAG&#39;, transform=transform) <br># Call the transform on the first observation in the datset<br>data = transform(dataset[0])</pre><p>I caution against attaching transforms directly to the dataset so that you don&#39;t make the same mistakes I did:</p><h3>Pre-process on Clean Data</h3><p>What the tutorials don’t consider is that people often do a lot of things with their datasets before starting to train on them. Attaching transforms directly to the dataset means your data will be augmented <em>anytime</em> you access it. This muddles crucial pre-processing steps such as normalization, standardization, and imputation <em>et al.</em> where you want to obtain static and reproducible constants. If you&#39;re calculating normalization constants on your training dataset and then applying those same constants for inference, the last thing you want is reproducibility issues. Before wising up I actually implemented this terrible sin several places in my pre-processing code to mitigate the issue - writing this blog is part of my atonement:</p><pre># Temporarily remove the transforms<br>original_transform = None <br>if dataset.transform is not None: <br>  original_transform = dataset.transform <br>  dataset.transform = None <br><br># Normalize data<br>... <br><br># Restore the transforms<br>dataset.transform = original_transform</pre><p>Don’t do this! Take control of your transforms and apply them only when you need to. Don&#39;t attach them at the hip of your dataset.</p><h3>Guard Your Original Data</h3><p>In the midst of handling transformations, it’s easy to overlook a crucial point: preserving the integrity of your original data. In-place transformations can inadvertently modify your data, leading to potential inconsistencies and headaches down the line. In my case, I found augmentations were being compounded epoch-by-epoch as my original data was overwritten. In fact, this mistake was carried on from official PyG examples I was building off. Fortunately, the PyG team was able to address the <a href="https://github.com/pyg-team/pytorch_geometric/pull/7429">issue</a>, which should hopefully be in the next release. In the meantime, remember to create shallow copies before you transform!</p><h3>Augment the Dataset, Not the Training Time</h3><p>Attaching transforms to your dataset seems like an intuitive and efficient approach, but losing control over when and where your augmentation is applied can mean significant slow downs with hidden causes. In my case, I had implemented a custom PyG Dataset class following the official PyG <a href="https://pytorch-geometric.readthedocs.io/en/latest/tutorial/create_dataset.html#:~:text=In%20Memory%20Datasets%E2%80%9D-,%EF%83%81,-In%20order%20to">example</a> where I had some attribute self.data_list which contained a list of independent graphs, represented by PyG Data objects. It was only after my epoch training time increased from 22 seconds to 38 minutes that I realized the data augmentations were being called for <em>every</em> graph in the data_list each time a <em>single</em> mini-batch was being loaded. I had never implemented a custom __getitem__ method in my custom dataset and was relying on inheriting the method from the base Dataset class. It had never failed me until I realized that it was indexing my entire data_list and applying transforms on it without my knowledge.</p><p>PyTorch and PyTorch Geometric Datasets are incredibly powerful tools with excellent flexibility, but that can make things go awry if you haven&#39;t stored your dataset in canonical ways, and even sometimes if you do. . . This was the last straw for me. I was determined to take control of the randomness in my life and call transform(data) explicitly!</p><h3>Composing Augmentation with PyTorch Lightningpy</h3><p>Lastly, let’s talk about <a href="https://lightning.ai/pytorch-lightning/">PyTorch Lightning</a>. While it’s a fantastic tool that simplifies a lot of the boilerplate code in PyTorch, it comes with its own quirks. Certain aspects require a little extra care and handling to ensure that your model training runs smoothly. Lightning abstracts away most of the training loop and requires users simply specify train_dataloader and val_dataloader methods to return some iterator, generally a PyTorch DataLoader. These methods can be implemented either directly in the LightningModule or in the optional LightningDataModule. After this, mini-batches are sampled and dispatched according to Lightning&#39;s smart &quot;auto&quot; acceleration strategies which generally means they end up where you want them to go, such as on the GPU/TPU.</p><p>Attaching transforms directly to your Dataset seems to fit in well with this paradigm and just like most things with PyTorch Lightning, somehow they are magically taken care of! The problem is when they are taken care of. Depending on the operations underpinning the augmentation strategies, it may be more efficient to apply them on the CPU or accelerator. Some augmentations, like those from <a href="https://github.com/kornia/kornia">Kornia</a> are designed to be entirely differentiable and may be faster operating directly on tensors already stored on the accelerator. Most strategies are best done on CPU which can take advantage of PyTorch&#39;s multiprocessing features built into DataLoader workers.</p><p>Lightning has implemented two very useful <a href="https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.core.hooks.DataHooks.html#datahooks">data hooks</a> which allow users to have more control over what happens when batches are loaded before and after they are sent to accelerators. These can be implemented as methods in either the LightningModule or the LightningDataModule:</p><pre># Operates on a mini-batch before it is transferred to the accelerator<br>on_before_batch_transfer(batch, dataloader_idx): <br><br># Operates on a mini-batch after it is transferred to the accelerator<br>on_after_batch_transfer(batch, dataloader_idx)</pre><p>Reading this excellent Lightning <a href="https://lightning.ai/docs/pytorch/stable/notebooks/lightning_examples/augmentation_kornia.html">tutorial</a> on batched data augmentation finally gave me the tools I needed to take full control of how my data augmentation was being performed. A simple additional hook in my LightningDataModule solved the last of my problems:</p><pre>def on_before_batch_transfer(self, batch: Any, dataloader_idx: int) -&gt; Any: <br>  &quot;&quot;&quot; <br>  Called before a batch is transferred to the device. <br>  We apply data augmentation here only during training. <br>  &quot;&quot;&quot; <br>  <br>  if self.trainer.training: <br>    batch = self.transforms(batch) <br>  return batch</pre><p>This ensured that my augmentation was performed (1) only on specific mini-batches as they are loaded, (2) not on validation or testing data, (3) on the correct hardware, and (4) only within the training loop.</p><h3>Conducting the Symphony of Randomness</h3><p>Randomness is not just fundamental to life but also embedded deep within machine learning craft. Respect and wield the power of randomness wisely. Balance it with stability and reproducibility. Navigating through the uncertain terrains of machine learning means not only adapting to randomness but also shaping it to our advantage. In doing so, we turn Poitier’s quote on its head: life may be determined by pure randomness, but we are its agent.</p><p>If you’re interested in more data science / python related blogs, please check out <a href="https://python-bloggers.com/">https://python-bloggers.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*F_lohhXt5_XPD0i_.jpg" /></figure><p>Anti-lumper nuance hunter. All opinions are my own.</p><p><em>Originally published at </em><a href="https://alecstashevsky.com/post/on-the-fly-augmentation-with-pytorch-geometric-and-lightning-what-tutorials-dont-teach/"><em>https://alecstashevsky.com</em></a><em> on June 4, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c61b0e09c7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Topology and Geometry Through Graph ML | Alec Stashevsky]]></title>
            <link>https://medium.com/@AlecStashevsky/topology-and-geometry-through-graph-ml-alec-stashevsky-c42da67882f9?source=rss-de9be4b48762------2</link>
            <guid isPermaLink="false">https://medium.com/p/c42da67882f9</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-machine-learning]]></category>
            <category><![CDATA[topology]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Alec Stashevsky]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 00:00:44 GMT</pubDate>
            <atom:updated>2024-04-04T01:54:44.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*FeI-2LGN-PmiAD-m-_uCyQ.png" /></figure><blockquote><em>There is no royal road to geometry.</em></blockquote><blockquote><em>- Euclid, </em>on account of Proclus of Athens</blockquote><p>This was Euclid’s response when asked by Ptolemy if no shorter road to geometry existed than through his <a href="http://aleph0.clarku.edu/~djoyce/elements/elements.html"><em>Elements.</em></a></p><p>For the past year I’ve been working with a team of folks at <a href="https://fetch.com/">Fetch</a> to develop and productionalize a machine learning based document understanding pipeline powering the core of the Fetch app. At Fetch, we reward our users for snapping pictures of their receipts in real-time, and we do the heavy lifting with this pipeline.</p><p>During this process, one of the things I’ve spent more time trying to do is understand unstructured data (such as images of receipts and the language which appears on them) in more elegant ways. This led me to a new and exciting place flourishing within the ML community: Graph Machine Learning (Graph ML).</p><p>This post is about some of the things I’ve learned participating in the Graph ML and Geometric Deep Learning communities. This post is also about some of the things I’ve had to forget when applying Graph ML in large-scale industrial settings.</p><h3>Graphs Are All Around Us</h3><p>When first learning about graphs, one usually encounters something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdsuZ1vdQNZSX8mXeqA1gQ.png" /></figure><p>A collection of <em>nodes</em> or <em>vertices</em> represented as dark green circles connected by <em>edges</em> or <em>links</em> which indicate some pairwise relationship between two nodes.</p><p>Graphs are incredibly simple yet flexible data structures. There is no notion of left, right, up, or down. Nodes and edges can be added or omitted as we please. We can also move, bend, and reorder the nodes without changing the underlying relational structure of the graph. That is, without changing the fundamental nature of the graph itself. For example, below I’ve moved some of the nodes of the graph around and switched node 3 and node 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzd9xAemODNvyeBBnxDZiA.png" /></figure><p>Despite these modifications, the graph describes the same basic relational structure. We refer to this underlying structure as the graph’s <em>connectivity</em> or the <em>topology</em> of the graph. The graph’s topology is agnostic of where we position these nodes in space, or what we name individual nodes.</p><p>This also means graphs exist outside of Euclidean space where we have explicit notions of distance and direction. I have no way of telling if node 3 is closer to node 4 or node 5 even though they appear farther apart in the two examples above. Graphs like these, in their most basic form, do not model Euclid’s geometry. Perhaps there is a shorter road after all?</p><h3>What Happens When We See Them</h3><p>One of the reasons Graph ML is such an exciting space is just how abundant graphs are. Graph ML is being used to model particle physics, where particles are represented as nodes and their physio-chemical interactions represented as edges. We also see social networks where user-profiles are nodes and their friendships, followers, or interactions form edges; financial networks with bank accounts as nodes and their transactions as edges of varying amounts; and even more recently, documents.</p><p>Where graphs can be seen, Graph ML is there to teach machines how to make conclusions about them and new unseen things we might later encounter. Graph ML is being used to <a href="https://towardsdatascience.com/drug-discovery-with-graph-neural-networks-part-1-1011713185eb">discover new therapeutic drugs</a>, <a href="https://cs.stanford.edu/~srijan/hoax/">prevent the spread of misinformation</a> in social networks (and probably also help it too), <a href="https://towardsdatascience.com/fraud-detection-with-graph-analytics-2678e817b69e">detect fraud</a> , and <a href="https://medium.com/mlearning-ai/what-is-ai-document-understanding-f32da5f12055">extract information from documents</a>.</p><p>As data scientists and machine learners, our main goal is to make sense of the world around us. We do some of that by building models in and through which our understanding may grow. When we begin to see graph structure and its natural projections onto the world, we unlock a deeper and more organic connection through which to explain and infer phenomena. Graphs unlock this connection by blending topological and geometric perspectives.</p><h3>Adding Geometry to Graphs</h3><p>For machines to learn on data, be it graph-structured or not, we must represent it in a way computers can digest. That is to say, we must encode the data into some <em>n</em>-dimensional Euclidean vector space where individual data points become vectors within that space.</p><p>Consider GPS telemetry data used to monitor the movement of a newly released California Condor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*1llYjTZK6UhAHXxr.jpeg" /></figure><p>The data used to make that visualization might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCiiHVIgh54q9gAHzXcqUw.png" /></figure><p>We want to represent each row in the table as a vector. However, the Latitude and Longitude coordinate system is part of a fundamentally <a href="https://www.esri.com/arcgis-blog/products/arcgis-pro/mapping/gcs_vs_pcs/">different type of geometry</a>: a non-Euclidean one native to the 3-dimensional ellipsoidal shape of the Earth. We can convert this non-Euclidean space to a 2-d Euclidean space in the traditional Cartesian coordinate system by using the <a href="https://openpress.usask.ca/introgeomatics/chapter/cartesianprojected-coordinate-systems-utm/">Universal Transverse Mercator (UTM)</a> map projection. The UTM projection gives us an <strong><em>(easting, northing) </em></strong>point for each point in <strong><em>(latitude, longitude) </em></strong>space.</p><p>After we have performed the mapping all of our data can be represented in a 5-d Euclidean vector space where each vector fully describes a row in our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJcHwFKecMqaBG4M09i47A.png" /></figure><p>This process introduces a consistent <em>geometry</em> to our data. That is, we can now understand our data through its shape, size, distance, and relative position. Below, I visualize the Condor GPS Telemetry vector space, using some liberties to represent the <em>Time</em> and <em>Condor</em> dimensions as hue and point-shape, respectively.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ealecalec34%2F8.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ealecalec34%2F8%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f98a92eaeabaaf393319640c3ddd13a1/href">https://medium.com/media/f98a92eaeabaaf393319640c3ddd13a1/href</a></iframe><p>Embedding our data into a vector space allows us to leverage Euclid’s <em>Elements</em> and everything built upon them. We can compare how similar two vectors are by using methods like <a href="https://towardsdatascience.com/understanding-cosine-similarity-and-its-application-fd42f585296a">cosine similarity</a> or feed these vectors into machine learning models as <em>features</em> to learn upon.</p><p>When our data has an inherent graph structure, the process is no different. We simply associate feature vectors with their given nodes or edges. Let’s take our first graph and re-imagine it as a representation of a small social network where nodes are user-profiles and edges indicate friendships between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ds1pix5oHnD9RNNDlgPZg.png" /></figure><p>For each node we have added a feature vector which holds some information about those user-profiles such as how long they have been on the platform <strong><em>x</em></strong>₁, when they last logged on <strong><em>x</em></strong>₂, their geographic region <strong><em>x</em></strong>₃, and so on.</p><p>Assigning feature vectors to the graph overlays a Euclidean geometry upon it. We can no longer move, bend, or switch nodes on the graph because each node now exists at a certain point in our feature-vector space. Moving the node would change its underlying meaning.</p><h3>Making Use of Topology and Geometry</h3><p>Graphs allow us to represent features alongside additional relationships and structure. Introducing a flexible topological structure in which Euclidean geometry can be embedded can help our models understand and generalize better.</p><p>Relational data is the most abundant type of data across industry, yet it is not often thought about in terms of its inherent graph structure. A simple database representation of our small social network below depicts the relational structure which can be explicitly embedded as the edges of a graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KcSgVCIlf2sbhzFh.png" /><figcaption>Each row in the user table (blue) holds information about a node in our graph while each row in the friendship table (green) represents an edge between the user who made the friend request and the user who accepted. Each user can have many friendships (shown by colored lines).</figcaption></figure><p>In this sense, all relational databases can be seen as graphs which allow for complex topologies through primary and foreign key relations like the one-to-many relationship we see above. The intuition behind adding this friendship-structure is that we can learn more about a user by also looking at who they are friends with and the attributes of those friends.</p><p>An extremely common modeling task on relational data of social networks is predicting <a href="https://medium.com/@malvikat/a-complete-guide-to-customer-churn-rate-fa6ec09d96d">user churn</a>. We want to know which users are likely to drop off the platform and perhaps intervene. A tabular machine learning model might ingest the rows of the user table as features and learn to recognize patterns about certain types of users and their behavior which makes them likely to attrite.</p><p>This may work relatively well, however, it ignores the underlying <em>topology of friendship</em> such a user finds themselves within. Consequently, we lose the ability to answer questions like: <em>if a user’s friends churn, are they more likely to churn themselves?</em> The graph-based approach allows us to answer this question because we can capture, for each row in the data, additional information about relationships between rows. <a href="https://alecstashevsky.com/post/topology-and-geometry-through-graph-ml/#ref-cvitkovic2020supervised">Cvitkovic</a> (<a href="https://alecstashevsky.com/post/topology-and-geometry-through-graph-ml/#ref-cvitkovic2020supervised">2020</a>) shows incorporating the connectivity of relational data through graphs is especially useful when many tables and foreign key relationships belong to a relational database.</p><p>Graphs unlock this capability by incorporating topological structure as an inductive bias <em>alongside</em> features rather than as an additional feature. Acknowledging the inherent topology of our data helps models better understand <em>how to learn</em> rather than expanding <em>what to learn</em>.</p><h3>Topology, All Along</h3><p>Topological structure need not conform to the Euclidean feature-space. Graphs force us to understand this through their non-Euclidean connectivity. However, a different kind of topology has been lurking alongside us along the way.</p><p>When we think about the data most machine learning operates on, such as tables, text, or images, we don’t usually speak about topology. That is because these data types all enforce a strict <em>regular topology</em> that doesn’t give us much signal to learn on. Images, for example, are represented as a regular grid of pixel values which can also be transformed into a graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cG-MxA3PQtn_Dh3w.png" /></figure><p>The structure of the pixel-grid will not change from image to image. That means the topology of the data can’t help us understand what the image is of. All of the signal which differentiates images is held in the 2-d Euclidean pixel-space rather than the topology of the pixel-space. The same case can be made for text data in a 1-d space, or any <em>n</em>-dimensional Euclidean vector space (like that of our Condor GPS telemetry) because there is always regular grid structure.</p><p>Machine learning canon evolved using Euclidean data and enforced this regular topology implicitly. The invariances of regular grid-structure were built into the models. As an artifact, much of machine learning has bound model architecture and input structure. <a href="https://flawnsontong.medium.com/what-is-geometric-deep-learning-b2adb662d91d">Geometric Deep Learning</a> is carving a different paradigm in which models are designed to understand and exploit the topological and geometric properties of their inputs. Models of this paradigm can adapt to different and more complex topology induced by graphs, <a href="https://www.cantorsparadise.com/an-invitation-to-group-theory-c81e21ab739a">symmetry groups</a>, and <a href="https://bjlkeng.github.io/posts/manifolds/">manifolds</a> while allowing for dynamic computation graphs.</p><h3>To Blog Is To Forget</h3><p>Looking back over the past year, I’d be remiss to not speak on the effects of entering into the fold through my own journey developing large-scale document AI systems. <em>Document AI</em> is a field which uses AI to comprehend documents such as <a href="https://guillaumejaume.github.io/FUNSD/">scanned invoices</a>, <a href="https://x-lance.github.io/WebSRC/">webpages</a>, <a href="https://data.nist.gov/pdr/lps/ark:/88434/mds2-2531">legal filings</a>, and in my experience: <a href="https://paperswithcode.com/dataset/sroie">receipts</a>. It is broad and touches a wide range of AI specialties: CV, NLP, and even more recently Graph ML.</p><p>Once brought into the fold of Graph ML, it can be hard to stop seeing graphs everywhere you look and especially hard to not send your CV and NLP colleagues blogs about how <a href="https://medium.com/@BorisAKnyazev/tutorial-on-graph-neural-networks-for-computer-vision-and-beyond-part-1-3d9fada3b80d">CNNs</a> and <a href="https://thegradient.pub/transformers-are-graph-neural-networks">transformers</a> are just special cases of graph neural networks. Yes, pretty much everything is a graph or can be molded into one but doing so isn’t always useful. Ignoring topology can help to not distract models (and the people who build them) when it lacks useful information. It also allows for highly optimized and parallelizable architectures rather than ones which are more flexible but must unfurl computation graphs dynamically.</p><p>Through sheer luck and an amazing group of colleagues and mentors, my past year led me to explore Graph ML and the Geometric Deep Learning paradigm to search for and uncover a hidden <em>semantic topology</em> within the documents we process. While I can’t say what this means for the future, I can say I have grown more than I could have imagined and I’m excited to see what 2023 holds.</p><p>As for Ptolemy, I’ve found another <a href="https://ai.stackexchange.com/questions/11226/what-is-non-euclidean-data/11259#11259">answer</a>. The shortest road between two points isn’t always a straight line. . .</p><h3>References</h3><p>Bronstein, Michael M., Joan Bruna, Yann LeCun, Arthur Szlam, and Pierre. Vandergheynst. 2016. “Geometric Deep Learning: Going Beyond Euclidean Data.” <em>CoRR</em> abs/1611.08097. <a href="http://arxiv.org/abs/1611.08097">http://arxiv.org/abs/1611.08097</a>.</p><p>Chen, Lu, Xingyu Chen, Zihan Zhao, Danyang Zhang, Jiabao Ji, Ao Luo, Yuxuan Xiong, and Kai Yu. 2021. “WebSRC: A Dataset for Web-Based Structural Reading Comprehension.” <em>CoRR</em> abs/2101.09465. <a href="https://arxiv.org/abs/2101.09465">https://arxiv.org/abs/2101.09465</a>.</p><p>Cvitkovic, Milan. 2020. “Supervised Learning on Relational Databases with Graph Neural Networks.” <em>arXiv Preprint arXiv:2002.02046</em>. <a href="https://doi.org/10.48550/arXiv.2002.02046">https://doi.org/10.48550/arXiv.2002.02046</a>.</p><p>Gemelli, Andrea, Sanket Biswas, Enrico Civitelli, Josep Lladós, and Simone Marinai. 2022. “Doc2Graph: A Task Agnostic Document Understanding Framework Based on Graph Neural Networks.” arXiv. <a href="https://doi.org/10.48550/ARXIV.2208.11168">https://doi.org/10.48550/ARXIV.2208.11168</a>.</p><p>Gens, Robert, and Pedro M Domingos. 2014. “Deep Symmetry Networks.” In <em>Advances in Neural Information Processing Systems</em>, edited by Z. Ghahramani, M. Welling, C. Cortes, N. Lawrence, and K. Q. Weinberger. Vol. 27. Curran Associates, Inc. <a href="https://proceedings.neurips.cc/paper/2014/file/f9be311e65d81a9ad8150a60844bb94c-Paper.pdf">https://proceedings.neurips.cc/paper/2014/file/f9be311e65d81a9ad8150a60844bb94c-Paper.pdf</a>.</p><p>Guillaume Jaume, Jean-Philippe Thiran, Hazim Kemal Ekenel. 2019. “FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents.” In <em>Accepted to ICDAR-OST</em>.</p><p>Hauser, Michael, and Asok Ray. 2017. “Principles of Riemannian Geometry in Neural Networks.” In <em>Advances in Neural Information Processing Systems</em>, edited by I. Guyon, U. Von Luxburg, S. Bengio, H. Wallach, R. Fergus, S. Vishwanathan, and R. Garnett. Vol. 30. Curran Associates, Inc. <a href="https://proceedings.neurips.cc/paper/2017/file/0ebcc77dc72360d0eb8e9504c78d38bd-Paper.pdf">https://proceedings.neurips.cc/paper/2017/file/0ebcc77dc72360d0eb8e9504c78d38bd-Paper.pdf</a>.</p><p>Heath, T. L. 2017. <em>Euclid’s Elements (the Thirteen Books)</em>. Digireads.com Publishing. <a href="https://books.google.com/books?id=04B9swEACAAJ">https://books.google.com/books?id=04B9swEACAAJ</a>.</p><p>Huang, Zheng, Kai Chen, Jianhua He, Xiang Bai, Dimosthenis Karatzas, Shijian Lu, and C. V. Jawahar. 2021. “Icdar2019 Competition on Scanned Receipt OCR and Information Extraction.” <em>CoRR</em> abs/2103.10213. <a href="https://arxiv.org/abs/2103.10213">https://arxiv.org/abs/2103.10213</a>.</p><p>Julia Elliott, Paul Mooney. 2021. “2021 Kaggle Machine Learning &amp; Data Science Survey.” Kaggle. <a href="https://kaggle.com/competitions/kaggle-survey-2021">https://kaggle.com/competitions/kaggle-survey-2021</a>.</p><p>Kumar, Srijan, Robert West, and Jure Leskovec. 2016. “Disinformation on the Web: Impact, Characteristics, and Detection of Wikipedia Hoaxes.” In <em>Proceedings of the 25th International World Wide Web Conference</em>.</p><p>Liu, Can, Li Sun, Xiang Ao, Jinghua Feng, Qing He, and Hao Yang. 2021. “Intention-Aware Heterogeneous Graph Attention Networks for Fraud Transactions Detection.” In <em>Proceedings of the 27th ACM SIGKDD Conference on Knowledge Discovery &amp; Data Mining</em>, 3280–88. KDD ’21. New York, NY, USA: Association for Computing Machinery. <a href="https://doi.org/10.1145/3447548.3467142">https://doi.org/10.1145/3447548.3467142</a>.</p><p>Morrow, Glenn R. 1992. <em>Proclus: A Commentary on the First Book of Euclid’s Elements</em>. Princeton University Press.</p><p>Shlomi, Jonathan, Peter Battaglia, and Jean-Roch Vlimant. 2020. “Graph Neural Networks in Particle Physics.” <em>Machine Learning: Science and Technology</em> 2 (2): 021001. <a href="https://doi.org/10.1088/2632-2153/abbf9a">https://doi.org/10.1088/2632-2153/abbf9a</a>.</p><p>Stokes, Jonathan M., Kevin Yang, Kyle Swanson, Wengong Jin, Andres Cubillos-Ruiz, Nina M. Donghia, Craig R. MacNair, et al. 2020. “A Deep Learning Approach to Antibiotic Discovery.” <em>Cell</em> 180 (4): 688–702.e13. https://doi.org/<a href="https://doi.org/10.1016/j.cell.2020.01.021">https://doi.org/10.1016/j.cell.2020.01.021</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*vekXgwjJ-BHEt43N.jpg" /></figure><p>Anti-lumper nuance hunter. All opinions are my own.</p><p><em>Originally published at </em><a href="https://alecstashevsky.com/post/topology-and-geometry-through-graph-ml/"><em>https://alecstashevsky.com</em></a><em> on December 9, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c42da67882f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[blocklength 0.1.4 | Alec Stashevsky]]></title>
            <link>https://medium.com/@AlecStashevsky/blocklength-0-1-4-alec-stashevsky-08a60fa55091?source=rss-de9be4b48762------2</link>
            <guid isPermaLink="false">https://medium.com/p/08a60fa55091</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Alec Stashevsky]]></dc:creator>
            <pubDate>Mon, 17 May 2021 00:00:15 GMT</pubDate>
            <atom:updated>2024-04-04T02:01:45.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*d5ZUcpv4FVems7xhB_YHLQ.png" /></figure><p>I’m excited to announce that blocklength 0.1.4 is now available on <a href="https://cran.r-project.org/package=blocklength">CRAN</a>! blocklength is designed to be used with block-bootstrap procedures and makes it quick and easy to select a block-length quantitatively.</p><p>Install it with:</p><pre>install.packages(&quot;blocklength&quot;)</pre><p>The most important changes are highlighted below and you can see a full list of changes in the <a href="https://alecstashevsky.com/r/blocklength/news">changelog</a>.</p><h3>Changes</h3><p>blocklength has received a fancy hex sticker! Thanks to <a href="https://www.linkedin.com/in/malina-cheeneebash-6a258a176/">Malina Cheeneebash</a>!</p><p>A new <a href="https://alecstashevsky.com/r/blocklength/articles/tuning-parameters">vignette</a> has been included on tuning and diagnosing problematic output from the block-length selection functions!</p><p>Some <a href="https://alecstashevsky.com/r/blocklength/news/#bug-fixes">bug fixes</a>.</p><h3>Acknowledgements</h3><p>A big thanks goes out to Malina Cheeneebash for designing the blocklength hex sticker! Also to <a href="https://www.simonpcouch.com/">Simon P. Couch</a> and <a href="https://www.linkedin.com/in/sergio-armella-647aa6122/">Sergio Armella</a> for their contributions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*q1Qw_CKmXEaHn7V5.jpg" /></figure><p>Anti-lumper nuance hunter. All opinions are my own.</p><p><em>Originally published at </em><a href="https://alecstashevsky.com/post/blocklength-0.1.4/"><em>https://alecstashevsky.com</em></a><em> on May 17, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08a60fa55091" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building my first R package | Alec Stashevsky]]></title>
            <link>https://medium.com/@AlecStashevsky/building-my-first-r-package-alec-stashevsky-dbe965c63936?source=rss-de9be4b48762------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbe965c63936</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Alec Stashevsky]]></dc:creator>
            <pubDate>Sun, 24 Jan 2021 00:00:36 GMT</pubDate>
            <atom:updated>2024-04-04T02:01:04.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*pf181KNcB68DcM-8bd1NDQ.png" /></figure><p>Recently, I began working with time series and found myself searching for a way to build confidence intervals around certain statistics I was interested in, like a series’ median. Many time series do not follow a known probability distribution so my mind went directly to using a bootstrap to estimate a sample variance. Here’s what I learned:</p><h3>The Bootstrap Method</h3><p>The bootstrap is a statistical technique used to infer characteristics of a population with a very limited set of assumptions about the sample data. The bootstrap does not require one to know (or guess) the underlying probability distribution of the data, and this is one of its greatest advantages. Using the bootstrap method, inference can be made without specifying any functional form. However, the assumptions that the regular bootstrap does require can be quite limiting in certain contexts like time series.</p><p>These contexts often present problems when observations are not independent and identically distributed <em>(i.i.d.),</em> a critical assumption of the regular bootstrap. The implications of the <em>i.i.d.</em> assumption are quite strong. We can say that observations are <em>independent</em> of eachother when the value of one observation has no effect on the value of other observations. This also means if we reorder the set of current observations this would have no effect on future observations, which is often not the case with time series.</p><p>One example of this is a random survey of individuals’ height. Certainly, there are characteristics that can influence how tall a person may be, such as age — but ultimately as we collect survey responses, the height of one respondent should not have an effect on the height of other respondents. In this sense, we can say that our survey responses are <em>independent</em> from each other. I will not go into all the implications of <em>i.i.d.</em> assumptions here, but I will say that topic of natural characteristics such as human heights being <em>i.i.d.</em> is full of nuance drawing out some of the implications such powerful statistical assumptions manufacture. If you would like to learn more, I encourage you to check out these posts on <a href="https://www.johndcook.com/blog/2008/07/20/why-heights-are-normally-distributed/">Why heights are normally distributed</a> and <a href="https://www.johndcook.com/blog/2008/07/20/why-heights-are-not-normally-distributed/">Why heights are not normally distributed.</a></p><h3>Why <strong>i.i.d.</strong> fails</h3><p>Let’s continue our random survey of human heights. For the next few years, we send out the height questionnaire every year to each randomly-selected respondent from our original survey. The data from the survey each year will be compiled into <em>panel-data</em> where respondents’ heights can now be tracked over a period of several years.</p><p>We have more data than had we just conducted the first survey, so we should be able to make stronger inferences than before, right? Well, not exactly. If we begin to conduct inferences about all human heights (population characteristics) using this collection of panel-data, we fail to recognize the underlying connections that have been introduced.</p><p>When we survey the same group of (originally) randomly-selected respondents each year, the height of a respondent this year should be related to their height in the previous year. Since humans generally grow in one direction we would expect the average height in our survey to only increase or stay relatively the same each year. This dynamic now violates our assumption of independence within the sample because each respondent’s answers will be connected. Panel-data and other types of data with inherent connections is characterized as <em>dependent data.</em></p><p>In practice, we could modify our survey design to target a different group of respondents each year removing such dependencies. However, this example illustrates a situation often encountered in time series analysis where processes are tracked over time and we cannot simply find unrelated processes within the data to help us answer questions about the original one.</p><p>In general, <em>i.i.d.</em> assumptions fail for many types of time series because we would expect the observation in the previous period to have some explanatory power over the current observation. I refer to this phenomenon as <em>time-dependence,</em> and it can could occur in many time series from unemployment rates, stock prices, biological data, etc. For example, we expect the water level of a river today to be somewhat close to the water level yesterday. The farther away from yesterday we go, the less related future water levels will be.</p><h3>Time-Dependence</h3><p>We can visualize what the <em>i.i.d</em> assumption looks like in time series by comparing time series with varying degrees of dependence on past observations. A time series that is completely <em>i.i.d.</em> looks like white noise, since each observation is completely random. We can compare this to a simulated time series with various degrees of <em>time-dependence:</em></p><pre># Generate i.i.d. time series<br>white.noise &lt;- ts(rnorm(500))<br><br># Generate AR(1) simulation<br>ar1.series &lt;- arima.sim(model = list(order = c(1, 0, 0),<br>  ar = 0.5), n = 500, rand.gen = rnorm)<br><br># Generate AR(5) simulation<br>ar5.series &lt;- arima.sim(model = list(order = c(5, 0, 0),<br>  ar = c(0.2, 0.2, 0.1, 0.1, 0.1)), n = 500)<br><br># Combine with time period<br>series &lt;- data.frame(<br>  &quot;Time&quot; = rep(1:500, 3),<br>  &quot;Series&quot; = factor(c(<br>    rep(&quot;White Noise&quot;, 500),<br>    rep(&quot;AR(1)&quot;, 500),<br>    rep(&quot;AR(5)&quot;, 500)),<br>    levels = c(&quot;White Noise&quot;, &quot;AR(1)&quot;, &quot;AR(5)&quot;)),<br>  &quot;Value&quot; = c(white.noise, ar1.series, ar5.series)</pre><p>Behind the scenes, I plot these three time series:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ealecalec34%2F2.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ealecalec34%2F2%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/26dfd0b2e3cec84d46fb3ebdcb64cef6/href">https://medium.com/media/26dfd0b2e3cec84d46fb3ebdcb64cef6/href</a></iframe><p>The top panel illustrates a perfectly <em>i.i.d.</em> time series, while the bottom two panels illustrate time series where each observation is somewhat dependent on the previous observations. These are called <em>autoregressive </em><strong><em>AR(p)</em></strong><em> </em>processes of order <strong><em>p</em></strong>. The order of the <strong><em>AR </em></strong>process defines the number of prior observations which have explanatory power over the current observation. The middle panel illustrates an <strong><em>AR(1)</em></strong> simulation, thus each observation depends on only the immediate prior observation. The bottom panel illustrates an <strong><em>AR(5)</em></strong> model with a higher autoregressive order where each observation is dependent on the previous five observations.</p><p>To some extent we can see the degree of <em>time-dependence</em> in each model. The top panel seems to oscillate much quicker and the periods of downward/upward trend are relatively short. If we compare this to the <strong><em>AR(1) </em></strong>model, somewhat more pronounced trends appear where observations are increasing or decreasing consistently for longer durations. In the <strong><em>AR(5) </em></strong>model, these trends seem even more drawn out. Though we can try to make visual comparisons because we understand the data-generating process behind these three time-series, in practice, this is often not the case and we must employ a battery of statistical tests to infer the degree of dependence — if any — within a given series.</p><h3>The Block Bootstrap</h3><p>To get around this problem, we can retain some of this time-dependence by breaking-up a time series into a number of blocks with length . Instead of sampling each observation randomly (with replacement) as in a regular bootstrap, we can resample these <em>blocks</em> at random. This way within each block the time-dependence is preserved. Below is a diagram from <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-article">El Anbari, Abeer, and Ptitsyn</a> ( <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-article">2015</a>) on a common block bootstrap method, the <em>moving block bootstrap (MBB).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*QopXOOpWHBsfmsNq.png" /></figure><p>In the moving block bootstrap, blocks are sampled from a set of overlapping blocks placed on top of the original time series. We can see this in the top panel where the yellow (5) and magenta (4) blocks both overlap with the cyan (2) block. In practice, a series of overlapping blocks will be laid over one another where each block increments one observation forward from the previous block, so that a total of blocks of length are laid over a time series with observations. A block bootstrap of this scheme is known as <em>Künsch’s rule.</em></p><p>The problem with the block bootstrap is the high sensitivity to the choice of block-length. If we decide to use blocks of half the length or double the length as depicted above, our bootstrap data may change dramatically and in turn any inference we perform.</p><p>This was exactly the problem I ran into several weeks ago working with benchmark interest rates. My plan was to use tseries::tsbootstrap() to block bootstrap the rates, but I found the results varied dramatically when I changed the block-length - and even worse - I had no reasoning to defend whatever block-length I selected.</p><h3>Choosing a Block-Length</h3><p>A hard-and-fast rule for the parameterization of block-length is still an unsolved problem; However, a variety of methods have been proposed in the econometric and statistical literature. I was able to find a selection of plug-in rules and algorithms to assess optimal blocks-lengths under various criteria. In their seminal paper, <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-10.1093/biomet/82.3.561">Hall, Horowitz, and Jing</a> (<a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-10.1093/biomet/82.3.561">1995</a>) show that the optimal asymptotic formula for block-length is proportional to <strong><em>n^(1/k) </em></strong>where<strong><em> k = {3,4,5}</em></strong> depending on the desired object of estimation. Moreover, <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-10.1093/biomet/82.3.561">Hall, Horowitz, and Jing</a> (<a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-10.1093/biomet/82.3.561">1995</a>) develop an empirically based algorithm to optimize the choice of block-length.</p><p>This was exactly what I needed, but a bit searching around CRAN, GitHub, and STATA and SAS libraries came up with nothing.</p><h3>Enter blocklength</h3><p>The goal of blocklength is to simplify and automate the process of selecting a block-length to bootstrap dependent data. blocklength is an R package with a set of functions to automatically select the optimal block-length for a bootstrap of suitable dependent data, such as <em>stationary</em> time series or dependent spatial data.</p><p>Currently, there are two methods available:</p><ol><li>hhj() takes its name from the <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-10.1093/biomet/82.3.561">Hall, Horowitz, and Jing</a> ( <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-10.1093/biomet/82.3.561">1995</a>) &quot;HHJ&quot; method to select the optimal block-length using a cross-validation algorithm which minimizes the mean squared error <strong><em>(MSE) </em></strong>incurred by the bootstrap at various block-lengths.</li><li>pwsd() takes its name from the <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-doi:10.1081/ETC-120028836">Politis and White</a> (<a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-doi:10.1081/ETC-120028836">2004</a>) Spectral Density &quot;PWSD&quot; Plug-in method to select the optimal block-length using spectral density estimation via &quot;flat-top&quot; lag windows of <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-https://doi.org/10.1111/j.1467-9892.1995.tb00223.x">Politis and Romano</a> ( <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-https://doi.org/10.1111/j.1467-9892.1995.tb00223.x">1995</a>).</li></ol><p>Under the hood, hhj() uses the moving block bootstrap (MBB) procedure according to <em>Künsch&#39;s rule,</em> which resamples blocks from a set of overlapping sub-samples with a fixed block-length. However, the results of hhj() may be generalized to other block bootstrap procedures such as the <em>stationary bootstrap</em> of <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-doi:10.1080/01621459.1994.10476870">Politis and Romano</a> ( <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-doi:10.1080/01621459.1994.10476870">1994</a>).</p><p>Compared to pwsd() , hhj() is more computationally intensive as it relies on iterative resampling processes that optimize the <strong><em>MSE </em></strong>function over each possible block-length (or a select grid of block-lengths). pwsd() is a simpler &quot;plug-in&quot; rule that uses the auto-correlations, auto-covariance, and the subsequent spectral density of the series to optimize the choice of block-length.</p><p>Currently, only the HHJ and PWSD methods are implemented through these two functions, but I plan on adding additional block-selection methods such as the Jackknife-after-bootstrap (JAB) Nonparametric Plug-in method proposed by <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-LAHIRI2007292">S. N. Lahiri, Furukawa, and Lee</a> ( <a href="https://alecstashevsky.com/post/building-my-first-r-package/#ref-LAHIRI2007292">2007</a>).</p><p>The package can be downloaded from my <a href="https://github.com/Alec-Stashevsky/blocklength">GitHub</a>.</p><p>If you are interested in more infoRmation, make sure to checkout <a href="https://www.r-bloggers.com/">R-bloggers</a> where you can find this post and many more!</p><h3>References</h3><p>El Anbari, Mohammed, Abeer Fadda, and Andrey Ptitsyn. 2015. “Confidence in Phase Definition for Periodicity in Genes Expression Time Series.” <em>PloS One</em> 10 (July): e0131111. <a href="https://doi.org/10.1371/journal.pone.0131111">https://doi.org/10.1371/journal.pone.0131111</a>.</p><p>Hall, Peter, Joel L. Horowitz, and Bing-Yi Jing. 1995. “On blocking rules for the bootstrap with dependent data.” <em>Biometrika</em> 82 (3): 561–74. <a href="https://doi.org/10.1093/biomet/82.3.561">https://doi.org/10.1093/biomet/82.3.561</a>.</p><p>Künsch, Hans R. 1989. “The Jackknife and the Bootstrap for General Stationary Observations.” <em>Ann. Statist.</em> 17 (3): 1217–41. <a href="https://doi.org/10.1214/aos/1176347265">https://doi.org/10.1214/aos/1176347265</a>.</p><p>Lahiri, S. K. 2003. <em>Resampling Methods for Dependent Data</em>. Springer Series in Statistics. Springer. <a href="https://books.google.com/books?id=e4f8sqm439UC">https://books.google.com/books?id=e4f8sqm439UC</a>.</p><p>Lahiri, S. N., K. Furukawa, and Y.-D. Lee. 2007. “A Nonparametric Plug-in Rule for Selecting Optimal Block Lengths for Block Bootstrap Methods.” <em>Statistical Methodology</em> 4 (3): 292–321. <a href="https://doi.org/10.1016/j.stamet.2006.08.002">https://doi.org/10.1016/j.stamet.2006.08.002</a>.</p><p>Politis, Dimitris N., and Joseph P. Romano. 1994. “The Stationary Bootstrap.” <em>Journal of the American Statistical Association</em> 89 (428): 1303–13. <a href="https://doi.org/10.1080/01621459.1994.10476870">https://doi.org/10.1080/01621459.1994.10476870</a>.</p><p>— — — . 1995. “Bias-Corrected Nonparametric Spectral Estimation.” <em>Journal of Time Series Analysis</em> 16 (1): 67–103. <a href="https://doi.org/10.1111/j.1467-9892.1995.tb00223.x">https://doi.org/10.1111/j.1467-9892.1995.tb00223.x</a>.</p><p>Politis, Dimitris N., and Halbert White. 2004. “Automatic Block-Length Selection for the Dependent Bootstrap.” <em>Econometric Reviews</em> 23 (1): 53–70. <a href="https://doi.org/10.1081/ETC-120028836">https://doi.org/10.1081/ETC-120028836</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*ceQl2Bjrpi02q_x1.jpg" /></figure><p>Anti-lumper nuance hunter. All opinions are my own.</p><p><em>Originally published at </em><a href="https://alecstashevsky.com/post/building-my-first-r-package/"><em>https://alecstashevsky.com</em></a><em> on January 24, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbe965c63936" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>