{"@attributes":{"version":"2.0"},"channel":{"title":"Stitch Fix Technology \u2013 Multithreaded","description":"Stitch Fix is a full-stack startup creating unique solutions in data-driven merchandising, massively scaled personal styling, and complex logistics.\n","link":"https:\/\/multithreaded.stitchfix.com\/","pubDate":"Wed, 10 Jun 2026 21:19:49 +0000","lastBuildDate":"Wed, 10 Jun 2026 21:19:49 +0000","generator":"Jekyll v3.10.0","item":[{"title":"Towards Service Deployment Agility","description":"<h1 id=\"introduction\">Introduction<\/h1>\n<p>At Stitch Fix, our data platform is designed to be self-service, with our users taking ownership of their own ETL, models, and microservices. To support this approach, the platform team prioritizes user autonomy and end-to-end tooling in their tooling designs, minimizing the involvement of platform engineers in day-to-day engineering and data science workflows.<\/p>\n\n<p>We regularly evaluate our infrastructure against new frameworks to assess the costs and benefits of potential updates. Last year, we transitioned our <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/03\/14\/spark-eks\/\">EMR-based Spark infrastructure to EKS<\/a> to take advantage of its benefits.  The next logical step was to re-examine how our core platform services were deployed and updated, especially those still deployed directly to instances.<\/p>\n\n<p>We also recognized that Kubernetes, a popular open-source system for handling the deployment of containerized applications, could provide benefits for microservice orchestration beyond just batch compute infrastructure.  Our existing instance-based service deployment framework was beginning to show its age in areas that were critical for Stitch Fix, such as the development lifecycle\u2019s velocity. As we saw an opportunity to leverage Kubernetes to address these issues, we identified pain points in our service deployment ecosystem.<\/p>\n\n<h2 id=\"pain-points\">Pain Points<\/h2>\n<ol>\n  <li>\n    <p><strong>Building and deploying services can be a time-consuming process<\/strong>, involving multiple steps and dependencies. We needed a solution that would streamline this process and enable us to deploy services more efficiently.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Polyglot environments<\/strong>, where multiple programming languages are used within the same system, can present a challenge for deployment standardization. At Stitch Fix, we use a variety of languages, including Python, Golang, Nodejs, and JVM (Java and Scala), making it difficult to establish consistent deployment practices across the board. We needed a way to deploy polyglot environments in a standardized and efficient manner.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Autoscaling and rollback capabilities<\/strong> are essential for managing service deployment at scale. At Stitch Fix, we found that our existing infrastructure had limited capabilities in these areas. We needed a solution that would enable us to easily scale services up and down as needed, and quickly rollback changes if necessary.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Traffic segmentation<\/strong> is an important aspect of service deployment, enabling us to direct traffic to different parts of our infrastructure based on various factors. However, we found that we were using different solutions for traffic segmentation across our various services, which created inconsistencies and added complexity to our infrastructure. We needed a solution that would enable us to manage traffic segmentation in a consistent and efficient manner.<\/p>\n  <\/li>\n<\/ol>\n\n<p>We evaluated industry options and were pleased to realize that we could address our pain points by adopting open source tools and applying a dash of Stitch Fix flavor. And, so we did: introducing the <strong>Service Operator Service (SOS)<\/strong>!<\/p>\n\n<h1 id=\"introducing-service-operator-service-sos\">Introducing: Service Operator Service (SOS)<\/h1>\n<h2 id=\"the-philosophy\">The Philosophy<\/h2>\n<p>SOS is a service deployment framework based on Kubernetes, designed to enable Stitch Fix data platform engineers, data engineers, and data scientists to manage their own deployment lifecycle through a self-service approach.<\/p>\n\n<p>With SOS, end users can interact with a streamlined set of tools, without the need to learn or be aware of Kubernetes. Meanwhile, maintainers can remain agile with industry-standard tools by leveraging cloud-native open-source software such as <a href=\"https:\/\/knative.dev\/\">Knative<\/a> and building on top of a thin layer of opinionated APIs. Knative offers a simplified abstraction that streamlines certain aspects of the Kubernetes application deployment process, including the management of network configurations.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <img src=\"\/assets\/posts\/2023-09-19-towards-service-deployment-agility\/sos-bov-architecture.png\" style=\"width: 100%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">Simplified diagram of the SOS architecture presenting the main components of the system.<\/figcaption>\n<\/figure>\n\n<h2 id=\"addressing-the-pain-points\">Addressing the Pain Points<\/h2>\n<p>The design of SOS focused on a set of key features centered around addressing our previously-detailed pain points:<\/p>\n\n<h3 id=\"fast-deployments\">Fast Deployments<\/h3>\n<p>Deployments in SOS are lightning-fast, thanks to two design decisions: we use Knative to reduce overhead, and we run all services as artifacts on standardized Docker images.<\/p>\n\n<p>Knative\u2019s quick pod provisioning is a major advantage, as we\u2019ve discovered firsthand - our deployments can be up and running in under 10 seconds. One of the ways Knative achieves this is by using a shared load balancer for all deployments, which reduces the overhead of deploying a new service.<\/p>\n\n<p>In SOS, each revision of a service is a self-contained artifact that runs on a curated Docker image specific to the service\u2019s language - Python, NodeJS, Golang, or JVM. This approach, while standard for Golang binaries and JVM jars, can be more challenging with Python due to its less-robust dependency management and portability issues.<\/p>\n\n<p>With this in mind, we set up a remote build process for each supported language that can compile an artifact on the same Docker image that the artifact would be run on. Each of the languages artifacts are defined as follows:<\/p>\n<ul>\n  <li>Golang - Golang binary<\/li>\n  <li>JVM - executable assembly jar file<\/li>\n  <li>Python - <a href=\"https:\/\/shiv.readthedocs.io\/en\/latest\/\">shiv archive<\/a> creates self-contained Python zipapps<\/li>\n  <li>NodeJS - <a href=\"https:\/\/github.com\/vercel\/ncc\">ncc<\/a> compiles a NodeJS project into a single file<\/li>\n<\/ul>\n\n<p>By bundling all dependencies within the artifact, we save significant time - anywhere from a few seconds to several minutes - that would otherwise be spent installing dependencies during runtime. As a result, services can enter a ready state more quickly. For services that have a more complex set of Python dependencies, we\u2019ve seen time savings of more than 5 minutes!<\/p>\n\n<h3 id=\"standardized-build-and-deployment-processes\">Standardized Build and Deployment Processes<\/h3>\n<h4 id=\"build-process\">Build Process<\/h4>\n<p>In addition to infrastructure work, we realized that for SOS to succeed, it was essential to offer a streamlined and straightforward method for users to create their artifacts. Without a standardized build and deploy process, users would have to sift through documentation to set up their local environments and handle processor architectures. We wanted to alleviate these overheads and provide users a least-resistance path to start experiencing SOS \u2013  batteries <em>are<\/em> included!<\/p>\n\n<p>To address this issue, we established a command-line tool where running <code class=\"language-plaintext highlighter-rouge\">sos build<\/code> in your project directory will automatically detect project metadata (such as if it\u2019s a Python or Golang deployment), perform integrity checks, and launch a remote build job that creates the SOS artifact on the same Docker image it would run on.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <img src=\"\/assets\/posts\/2023-09-19-towards-service-deployment-agility\/sos-build-deploy.png\" style=\"width: 100%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">We standardized the build process with a command-line tool that initiates remote build jobs, reducing user overhead in setting up environments and mitigating compatibility issues between runtime environments.<\/figcaption>\n<\/figure>\n\n<h4 id=\"deploy-process\">Deploy Process<\/h4>\n<p>We offer two interfaces for creating and updating service deployments in SOS: a Python client and a web-based UI built with React.<\/p>\n\n<p>The Python client allows users to declare their services as a DSL in a familiar Python ecosystem. To ensure consistent types, we synchronize data models between the SOS client and the SOS API using shared protobuf files. We will cover the Python client\u2019s user interface in more detail later.<\/p>\n\n<p>Our web-based UI allows users to easily review revision histories and adjust traffic policies. We have ensured feature parity between the Python client and the web UI, enabling our users to choose the interface that suits them best.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <img src=\"\/assets\/posts\/2023-09-19-towards-service-deployment-agility\/sos-ui.png\" style=\"width: 100%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">Our UI provides an alternative way to easily manage deployments. This screenshot shows how the UI can be used to adjust the traffic segmentation between different revisions.<\/figcaption>\n<\/figure>\n\n<h3 id=\"traffic-segmentation-and-responsive-autoscaling-over-multiple-axes\">Traffic Segmentation and Responsive Autoscaling Over Multiple Axes<\/h3>\n<p>SOS included traffic segmentation and responsive scaling as a key feature for several reasons. These features enabled faster deployments and rollbacks, which facilitated shorter development cycles. Moreover, because all metrics and logs are namespaced by the traffic segmentation, we gained much better insights into service behavior. This feature also made gradual traffic cutovers possible and allowed for fast autoscaling to handle traffic bursts while reducing costs by scaling down unused instances.<\/p>\n\n<p>For example, by setting services to use a minimum of zero instances, it is possible to make SOS services serverless. No pods would be provisioned until they receive traffic. Implementing this feature for our services allowed us to save significant costs on staging deployments and production services that receive less constant traffic.<\/p>\n\n<h1 id=\"the-sos-user-experience\">The SOS User Experience<\/h1>\n<h2 id=\"blissful-ignorance\">Blissful Ignorance<\/h2>\n<p>Users don\u2019t need to be aware that SOS runs on Kubernetes - all they need to do to start deploying services is install the SOS Python client!<\/p>\n\n<h2 id=\"decoupled-application-and-system\">Decoupled Application and System<\/h2>\n<p>SOS ensures that each user\u2019s new code deployment is immutable and has a unique ID, tied to an SOS artifact with its own dependencies. This decouples the system and application, setting clear boundaries and avoiding the issue of Nginx configs and secrets management bundled into an application\u2019s source code that we faced with our previous instance-based deployment.<\/p>\n\n<p>We wanted to avoid a scenario where users inherit and patch and layers of Docker images until they become unmaintainable black boxes. By running all service artifacts on top of curated Docker images, we avoided the problem of users managing their own Docker images. This made it easier to implement platform-wide changes over time, as we could patch and improve the Docker images without relying on users to rebuild their applications. This also allowed us to efficiently tweak and fine-tune the observability agents on the system.<\/p>\n\n<h2 id=\"single-source-of-truth\">Single Source of Truth<\/h2>\n<p>The SOS service itself is the source of truth for each deployment, so users don\u2019t need to manage multiple configurations for the same service. When deploying a service, the SOS service will merge any necessary files at the service level, which prevents confusion that can arise when configuration files are stored in different branches or exist only in a user\u2019s local environment.<\/p>\n\n<h2 id=\"the-experience\">The Experience<\/h2>\n<p>The SOS Python client is the tool that our users use to interact with SOS. Below are some examples of the SOS Python client and how a user would use it to define their service deployment.<\/p>\n\n<h3 id=\"service-creation\">Service Creation<\/h3>\n<p>Each SOS service correlates with a service that\u2019s created in Kubernetes.<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"n\">service<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Service<\/span><span class=\"p\">(<\/span>\n  <span class=\"nb\">id<\/span><span class=\"o\">=<\/span><span class=\"s\">\"sfix_service\"<\/span><span class=\"p\">,<\/span>\n  <span class=\"n\">owner_id<\/span><span class=\"o\">=<\/span><span class=\"s\">\":team:sfix_team_name\"<\/span><span class=\"p\">,<\/span>\n  <span class=\"n\">env<\/span><span class=\"o\">=<\/span><span class=\"s\">\"prod\"<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">)<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<h3 id=\"creating-a-revision\">Creating a Revision<\/h3>\n<p>In SOS, a service can have multiple revisions, with each revision representing an immutable version of the service that can be deployed independently.<\/p>\n\n<p>The example below shows the minimal configurations to create a revision that deploys a Python artifact. The <code class=\"language-plaintext highlighter-rouge\">Artifact<\/code> is a self-contained Python artifact that has been deployed to Artifactory, which we use as our sink of artifacts.<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"n\">revision<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Revision<\/span><span class=\"p\">(<\/span>\n  <span class=\"nb\">id<\/span><span class=\"o\">=<\/span><span class=\"s\">\"sfix_service-5\"<\/span><span class=\"p\">,<\/span>\n  <span class=\"n\">artifact<\/span><span class=\"o\">=<\/span><span class=\"n\">Artifact<\/span><span class=\"p\">(<\/span><span class=\"n\">name<\/span><span class=\"o\">=<\/span><span class=\"s\">\"sfix_service\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">version<\/span><span class=\"o\">=<\/span><span class=\"s\">\"v0.0.16\"<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">python_config<\/span><span class=\"o\">=<\/span><span class=\"n\">PythonConfig<\/span><span class=\"p\">(<\/span>\n          <span class=\"n\">python_version<\/span><span class=\"o\">=<\/span><span class=\"s\">\"3.9\"<\/span><span class=\"p\">,<\/span>\n          <span class=\"n\">gunicorn_config<\/span><span class=\"o\">=<\/span><span class=\"n\">GunicornConfig<\/span><span class=\"p\">(<\/span><span class=\"n\">worker_class<\/span><span class=\"o\">=<\/span><span class=\"s\">\"gevent\"<\/span><span class=\"p\">),<\/span>\n          <span class=\"n\">app_module<\/span><span class=\"o\">=<\/span><span class=\"s\">\"sfix_service.server:app\"<\/span><span class=\"p\">,<\/span>\n  <span class=\"p\">),<\/span>\n<span class=\"p\">)<\/span>\n\n<span class=\"n\">logging<\/span><span class=\"p\">.<\/span><span class=\"n\">info<\/span><span class=\"p\">(<\/span><span class=\"n\">service<\/span><span class=\"p\">.<\/span><span class=\"n\">add_revision<\/span><span class=\"p\">(<\/span><span class=\"n\">revision<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>Additional settings can be configured for more complex deployments, such as port number, environment variables, memory and CPU allocation, health checks, and thread and worker counts. Here\u2019s an example of how to set these configurations:<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"n\">revision<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Revision<\/span><span class=\"p\">(<\/span>\n  <span class=\"nb\">id<\/span><span class=\"o\">=<\/span><span class=\"s\">\"sfix_service-5\"<\/span><span class=\"p\">,<\/span>\n  <span class=\"n\">artifact<\/span><span class=\"o\">=<\/span><span class=\"n\">Artifact<\/span><span class=\"p\">(<\/span><span class=\"n\">name<\/span><span class=\"o\">=<\/span><span class=\"s\">\"sfix_service\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">version<\/span><span class=\"o\">=<\/span><span class=\"s\">\"v0.0.16\"<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">container<\/span><span class=\"o\">=<\/span><span class=\"n\">Container<\/span><span class=\"p\">(<\/span>\n          <span class=\"n\">port<\/span><span class=\"o\">=<\/span><span class=\"mi\">5001<\/span><span class=\"p\">,<\/span>\n          <span class=\"n\">env_vars<\/span><span class=\"o\">=<\/span><span class=\"p\">[<\/span><span class=\"n\">EnvVar<\/span><span class=\"p\">(<\/span><span class=\"nb\">id<\/span><span class=\"o\">=<\/span><span class=\"s\">\"env_var\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">value<\/span><span class=\"o\">=<\/span><span class=\"s\">\"env_value\"<\/span><span class=\"p\">)],<\/span>\n          <span class=\"n\">resources<\/span><span class=\"o\">=<\/span><span class=\"n\">Resources<\/span><span class=\"p\">(<\/span><span class=\"n\">memory<\/span><span class=\"o\">=<\/span><span class=\"s\">\"2G\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">cpu<\/span><span class=\"o\">=<\/span><span class=\"s\">\"1000m\"<\/span><span class=\"p\">),<\/span>\n  <span class=\"p\">),<\/span>\n  <span class=\"n\">health_check<\/span><span class=\"o\">=<\/span><span class=\"n\">HealthCheck<\/span><span class=\"p\">(<\/span><span class=\"n\">liveness_probe<\/span><span class=\"o\">=<\/span><span class=\"s\">\"\/\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">readiness_probe<\/span><span class=\"o\">=<\/span><span class=\"s\">\"\/\"<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">sf_env<\/span><span class=\"o\">=<\/span><span class=\"s\">\"prod\"<\/span><span class=\"p\">,<\/span>\n  <span class=\"n\">python_config<\/span><span class=\"o\">=<\/span><span class=\"n\">PythonConfig<\/span><span class=\"p\">(<\/span>\n          <span class=\"n\">python_version<\/span><span class=\"o\">=<\/span><span class=\"s\">\"3.9\"<\/span><span class=\"p\">,<\/span>\n          <span class=\"n\">gunicorn_config<\/span><span class=\"o\">=<\/span><span class=\"n\">GunicornConfig<\/span><span class=\"p\">(<\/span><span class=\"n\">worker_count<\/span><span class=\"o\">=<\/span><span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"n\">thread_count<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">,<\/span> <span class=\"n\">worker_class<\/span><span class=\"o\">=<\/span><span class=\"s\">\"gevent\"<\/span><span class=\"p\">),<\/span>\n          <span class=\"n\">app_module<\/span><span class=\"o\">=<\/span><span class=\"s\">\"sfix_service.server:app\"<\/span><span class=\"p\">,<\/span>\n  <span class=\"p\">),<\/span>\n  <span class=\"n\">autoscaling<\/span><span class=\"o\">=<\/span><span class=\"n\">Autoscaling<\/span><span class=\"p\">(<\/span><span class=\"n\">min_scale<\/span><span class=\"o\">=<\/span><span class=\"mi\">6<\/span><span class=\"p\">),<\/span>\n<span class=\"p\">)<\/span>\n\n<span class=\"n\">logging<\/span><span class=\"p\">.<\/span><span class=\"n\">info<\/span><span class=\"p\">(<\/span><span class=\"n\">service<\/span><span class=\"p\">.<\/span><span class=\"n\">add_revision<\/span><span class=\"p\">(<\/span><span class=\"n\">revision<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<h3 id=\"set-traffic-for-new-revision\">Set Traffic for New Revision<\/h3>\n<p>We recognized the importance of providing robust support for traffic segmentation, as users should have confidence that deploying new code wouldn\u2019t negatively impact their entire system. By giving them complete control over the flow of traffic, they could confidently iterate on changes without fear of breaking everything. This was crucial to enabling faster development cycles and smoother rollbacks, as well as improving our understanding of service behavior through fine-grained traffic analysis.<\/p>\n\n<p>The following example shows how the newly created revision can be set to receive 100% traffic. However, to roll out changes more safely, traffic can be segmented between multiple revisions by adding more Route objects to the TrafficRoute.routes configuration. SOS\u2019s observability tooling can be used to monitor the traffic and ensure a smooth transition.<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"n\">service<\/span><span class=\"p\">.<\/span><span class=\"n\">add_traffic<\/span><span class=\"p\">(<\/span>\n    <span class=\"n\">Traffic<\/span><span class=\"p\">(<\/span>\n        <span class=\"n\">traffic_route<\/span><span class=\"o\">=<\/span><span class=\"n\">TrafficRoute<\/span><span class=\"p\">(<\/span>\n            <span class=\"n\">routes<\/span><span class=\"o\">=<\/span><span class=\"p\">[<\/span>\n                <span class=\"n\">Route<\/span><span class=\"p\">(<\/span>\n                    <span class=\"n\">percent<\/span><span class=\"o\">=<\/span><span class=\"mi\">100<\/span><span class=\"p\">,<\/span>\n                    <span class=\"n\">revision_id<\/span><span class=\"o\">=<\/span><span class=\"s\">\"sfix_service-5\"<\/span><span class=\"p\">,<\/span>\n                    <span class=\"n\">dns_record_suffix<\/span><span class=\"o\">=<\/span><span class=\"s\">\"active\"<\/span><span class=\"p\">,<\/span>\n                <span class=\"p\">),<\/span>\n            <span class=\"p\">]<\/span>\n        <span class=\"p\">),<\/span>\n    <span class=\"p\">)<\/span>\n<span class=\"p\">)<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<h1 id=\"the-present-and-the-future\">The Present and the Future<\/h1>\n<p>Most data platform services have already been migrated to SOS.  It hosts many critical services, including the components of our batch processor, <a href=\"https:\/\/github.com\/stitchfix\/flotilla-os\">job execution engine<\/a>, our metastore, configuration management service, Kafka connect cluster, ownership discovery service, and more! While there are some data science services deployed on SOS, most of the currently-deployed services are focused on powering our data platform.<\/p>\n\n<p>SOS aims to streamline the service lifecycle, yet its opinionated approach might not suit all deployments. Certain open-source tools align better with standard industry patterns. For instance, we deploy Trino directly onto Kubernetes and use a Helm Chart for Airflow. While SOS isn\u2019t a one-size-fits-all solution, it remains highly effective for the majority of our existing and future deployments.<\/p>\n\n<p>We are regularly improving the user experience of SOS by migrating existing services and building new ones on top of it. Our goal is to reduce the complexity of service deployment and continue to empower our data scientists and engineers at Stitch Fix to be more efficient and effective.<\/p>\n","pubDate":"Tue, 19 Sep 2023 15:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/09\/19\/towards-service-deployment-agility\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/09\/19\/towards-service-deployment-agility\/"},{"title":"Ariadne: building a custom observability UI for personalized search","description":"<p>In June 2022, Stitch Fix launched the Freestyle search feature, transforming how our clients \ndiscover styles that are tailored to their taste. Under the hood, personalized search is \nfulfilled by a pipeline of modular microservices. We designed the search system to be \ncomposable, making it easy to swap in new components and speeding up experimentation and \ndevelopment. Composability also made the system more observable, making it simpler to make \neach event traceable and reproducible with built-in logging and metrics. \nHowever, even with extensive logging, debugging a complex system such as personalized search \ncan be quite challenging.<\/p>\n\n<p>As a hypothetical  example, if a client searches for running shoes and instead sees \npaisley sweaters, we need to quickly diagnose where in the search pipeline the problem occurred, \nso that the experts in that system can work on a resolution. Where did the sweaters come from, \nand where are the shoes we expected to see instead? Did the query get parsed into incorrect \nattributes? Did the attributes get poorly matched with items in our inventory? Did the result \nrankings disproportionately focus on the client\u2019s past preference for sweaters and disinterest \nin sportswear? Understanding which service is responsible for the problem is a crucial first \nstep in addressing it. Ideally, we want to anticipate and prevent such problems through \ninterrogating hypothetical search scenarios before clients encounter them.<\/p>\n\n<p>Early on, we knew that slogging through system logs to understand bugs and dependencies \nof search would not sustain our need for iterative experimentation and collaborative development. \nTo reduce toil and enhance the impact of the Search team, we invested in building a dedicated \ntool. Ariadne, named after the labyrinth expert from Greek mythology, is a custom interactive \nUI designed for search introspection. Ariadne is built with React and custom visualization \ncomponents based on D3.js, visx, and internal libraries, and is powered by production and \nexperimental search APIs. Developing alongside search, Ariadne has assisted our data scientists, \nengineers, UX researchers, designers, and product managers through launch, development, \nand continued experimentation.<\/p>\n\n<p>In developing Ariadne, we have prioritized several capabilities needed to support \nand amplify the work of the Search team. In this article, we will show how Ariadne \nfulfills the following user needs:<\/p>\n<ol>\n  <li>Provide a holistic view of the complete search pipeline from query to results;<\/li>\n  <li>Make it easy to identify the pipeline component that is \u201cresponsible\u201d for anomalous results;<\/li>\n  <li>Explore search results visually and by comparing metric distributions;<\/li>\n  <li>Focus on specific items and their journey through the search pipeline \n(e.g. if an expected item is not present in the search results, pinpoint \nwhere and why did it get blocked);<\/li>\n  <li>Enable \u201cwhat if\u201d analysis by modifying the search query, client, pipeline \nconfiguration and settings, and\/or specific inventory items.<\/li>\n<\/ol>\n\n<h3 id=\"search-pipeline-from-query-to-results\">Search pipeline from query to results<\/h3>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <img src=\"\/assets\/posts\/2023-06-14-ariadne\/hero_ariadne_blog.png\" width=\"100%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">\n        Search engineers start with searching for a query (e.g. \u201cplaid shacket\u201d) for a particular \n        client. The landing page shows how the search pipeline, uniquely configured for that client, \n        transforms the query into search results. Several interactively linked visualizations of \n        the processes and results and high information density support quick \n        triage and analysis\n    <\/figcaption>\n<\/figure>\n\n<p>The Sankey (aka flow) diagram at the top of the landing page shows how the search query \nis handled by each service in the pipeline. When problems arise, this view helps diagnose \nwhich service in the pipeline is at the root of the issue. While we use many pipeline \nconfigurations at Stitch Fix, the basic pipeline is composed of three services: querious, \nthe query parsing service, elastic, the core search engine backed by ElasticSearch, \nand tailor-sift, the personalized reranking service.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <img src=\"\/assets\/posts\/2023-06-14-ariadne\/sankey_diagram.png\" width=\"100%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">\n        Sankey diagram section, left. Search query \u201cplaid shacket\u201d is parsed into weighted \n        subqueries recognized by the querious service: \u201c[291] full_text: plaid\u201d, \n        \u201c[291] full text: shacket\u201d, \u201c[345] gpc_class: Upper Body Wear\/Tops\u201d, \n        \u201c[345] print_name: Plaid\u201d. The numbers in brackets indicate entity weights. \n        Other recognized entities with lower weights are hidden by default.\n    <\/figcaption>\n<\/figure>\n\n<p>First, the search query \u201cplaid shacket\u201d is parsed by querious into weighted subqueries \n(named entities), e.g. \u201cclient comments: plaid\u201d, \u201cprint name: Plaid\u201d, \u201cgpc class: \nUpper Body Wear \/ Tops\u201d (\u201cshacket\u201d is a fashion term referring to a combination of \na shirt and a jacket). The width of each link from the search query to each subquery \nrepresents the weight of the subquery. This section of the Sankey diagram helps identify \nunexpected or improper weighting or errors in named entity recognition. For example, \nif search results contained paisley sweaters and we saw \u201cprint name: Paisley\u201d in this \ndiagram with a high weight, that would indicate that querious improperly identified paisley, \na wildly different print from plaid, as highly relevant.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\"> \n    <video playsinline=\"\" autoplay=\"\" loop=\"\" muted=\"\" poster=\"\/assets\/posts\/2023-06-14-ariadne\/sankey_video_poster.png\" style=\"max-width: 100%;\">\n        <source src=\"\/assets\/posts\/2023-06-14-ariadne\/sankey_video.mp4\" type=\"video\/mp4\" \/>\n        <p>\n            Your browser doesn't support HTML5 video. Here is a\n            <a href=\"\/assets\/posts\/2023-06-14-ariadne\/sankey_video.mp4\">link to the video<\/a> instead.\n        <\/p>\n  <\/video>\n    \n<figcaption style=\"margin-top: 0.5rem; text-align: center;\">\n    Sankey diagram section, right. The core search engine (elastic) ranks items in \n    the inventory based on the weighted subqueries identified by querious. \n    The core search engine then selects a set of top items, shown in the middle \n    column of nodes (top 50 items displayed). These items are then re-ranked by \n    the tailor-sift service to obtain final search results, shown in the right \n    column of nodes.\n<\/figcaption>\n<\/figure>\n\n<p>Next, subqueries identified by querious are handed off to the core search engine, \nbacked by ElasticSearch. The core search engine scores and ranks all items available \nin our inventory based on their correspondence to the weighted subqueries. \nThe top items are then selected for personalization. These items are either \nshown in the diagram as individual nodes, or can be grouped by attributes such as \ncolor or product group. In the latter case, the link width indicates the number \nof items in each group, providing a quick gut check for an expected distribution \nof results. For example, if we saw many search results falling into the product groups \n\u201cdresses\u201d and \u201cbottoms\u201d while querious only weighted \u201cupper body wear\u201d highly, \nwe would know that there is an issue with the core search engine rankings.<\/p>\n\n<p>Finally, tailor-sift reranks the items selected by the core search engine. \nThis reranking is uniquely tailored to each Stitch Fix client, relying on their past \npreferences and our algorithmic understanding of their style journey. \nVisual reordering of items in the Sankey diagram between the core search engine and \ntailor-sift illustrates how the search pipeline balances relevance and personalization. \nThat helps reveal potential issues with the reranking algorithm. For example, if the \norder of the results were reversed, that would indicate an excessive bias towards \npersonalization, potentially producing irrelevant results.<\/p>\n\n<h3 id=\"exploring-search-results\">Exploring search results<\/h3>\n\n<p>At the bottom of the landing page, search results are displayed in several ways for \nfurther exploration. These visualizations are linked with each other and the Sankey \ndiagram: selecting an item or subset of items in the pipeline visualization highlights \nthese items in the result views, and vice versa. This linking speeds up analysis by \nallowing the user to focus on a small number of items from any view and simultaneously \naccess information about these items across visualizations.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <img src=\"\/assets\/posts\/2023-06-14-ariadne\/sreach_results.png\" width=\"100%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">\n        Individual search result items are shown with their images, metadata, and \n        a set of metrics. In this view, results returned by the core search engine \n        can be compared with results reranked by tailor-sift.\n    <\/figcaption>\n<\/figure>\n\n<p>The first view of the search results is a tiled display of thumbnail cards with associated \nmetadata and metrics computed by the search pipeline. Fashion inventory is visually rich, \nand the thumbnail display conveys a great deal of information, making outliers in color, \nprint, or style readily apparent. The cards can be ordered by different metrics \nto understand how personalization affects the selection.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <video playsinline=\"\" autoplay=\"\" loop=\"\" muted=\"\" poster=\"\/assets\/posts\/2023-06-14-ariadne\/beeswarm_video_poster.png\" style=\"max-width: 100%;\">\n        <source src=\"\/assets\/posts\/2023-06-14-ariadne\/beeswarm_video.mp4\" type=\"video\/mp4\" \/>\n        <p>\n            Your browser doesn't support HTML5 video. Here is a\n            <a href=\"\/assets\/posts\/2023-06-14-ariadne\/beeswarm_video.mp4\">link to the video<\/a> instead.\n        <\/p>\n  <\/video>\n    \n<figcaption style=\"margin-top: 0.5rem; text-align: center;\">\n    Search result metrics are displayed via interactive beeswarm plots, \n    where each dot represents a metric computed by the search pipeline for an \n    individual item. Selecting any individual item focuses the investigation on that \n    item in other views as well.\n<\/figcaption>\n<\/figure>\n\n<p>In the second view of the search results, metrics computed by the search pipeline for \neach item are displayed using beeswarm plots. Each dot corresponds to a metric for an \nindividual item. Selecting an item highlights all metrics for that item, in addition \nto selecting that item in other visualizations. The distribution plots help identify \nanomalies in metric distributions. The plots reveal If any of the metrics were missing, \nskewed towards an end of the distribution, or clipped by improper data processing.<\/p>\n\n<h3 id=\"deep-dive-specific-items-in-the-search-pipeline\">Deep dive: specific items in the search pipeline<\/h3>\n\n<p>Often, there is a specific item or small set of items that we would like to focus on when \nanalyzing search results. For example, when expected items are not showing up in search \nresults, we need to understand why the problem occurred. It is possible that these items \nhave not appeared as candidates for the search results at all, that their relevance was \nscored incorrectly by the core search engine, or they were filtered out by personalized \nreranking. We can pinpoint the issue by comparing search metrics computed by each service \nfor the items of interest.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <video playsinline=\"\" autoplay=\"\" loop=\"\" muted=\"\" poster=\"\/assets\/posts\/2023-06-14-ariadne\/parallel_coor_poster.png\" style=\"max-width: 100%;\">\n        <source src=\"\/assets\/posts\/2023-06-14-ariadne\/parallel_coor.mp4\" type=\"video\/mp4\" \/>\n        <p>\n            Your browser doesn't support HTML5 video. Here is a\n            <a href=\"\/assets\/posts\/2023-06-14-ariadne\/parallel_coor.mp4\">link to the video<\/a> instead.\n        <\/p>\n  <\/video>\n    \n<figcaption style=\"margin-top: 0.5rem; text-align: center;\">\n    Parallel coordinates visualization of search metrics for a specific set of items. \n    Displayed metrics and color scales are customizable.\n<\/figcaption>\n<\/figure>\n\n<p>In Ariadne, metrics for specific items or sets of items can be compared in a parallel \ncoordinates plot. The plot shows either the full set of search results, items selected \nvia other visualizations, or any custom set of items (not limited to those appearing in \nsearch results). In this view, it is easy to see where missing items have terminated their \npath through the pipeline. Additionally, metrics can be customized, addressing other \nanalysis needs. For example, focusing solely on ranking metrics is helpful for understanding \nhow well the search pipeline balances relevance with personalization.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <video playsinline=\"\" autoplay=\"\" loop=\"\" muted=\"\" poster=\"\/assets\/posts\/2023-06-14-ariadne\/explain_poster.png\" style=\"max-width: 100%;\">\n        <source src=\"\/assets\/posts\/2023-06-14-ariadne\/explain.mp4\" type=\"video\/mp4\" \/>\n        <p>\n            Your browser doesn't support HTML5 video. Here is a\n            <a href=\"\/assets\/posts\/2023-06-14-ariadne\/explain.mp4\">link to the video<\/a> instead.\n        <\/p>\n  <\/video>\n    \n<figcaption style=\"margin-top: 0.5rem; text-align: center;\">\n    Interactive table showing relevance scores for individual items and subqueries \n    computed by the core search engine for the query \u201cplaid shacket\u201d.\n<\/figcaption>\n<\/figure>\n\n<p>While debugging and improving search, we often need to investigate how well the core \nsearch engine computes relevance for a particular set of items. The core search engine \nis backed by ElasticSearch and assigns a relevance score to each item paired with a subquery \nthat was parsed from the search query. Ariadne displays contributions of each subquery and \neach item\u2019s metadata to the item\u2019s overall relevance rank in an interactive table. \nThe table shows all search results by default, and any custom set of items can be substituted. \nThis makes it easy to spot missing data, unexpected mappings between subqueries and results, \nand inappropriate weight assignments.<\/p>\n\n<h3 id=\"what-if-analysis-and-pipeline-modification\">\u201cWhat if\u201d analysis and pipeline modification<\/h3>\n\n<figure style=\"margin-bottom: 1rem;\">\n    <video playsinline=\"\" autoplay=\"\" loop=\"\" muted=\"\" poster=\"\/assets\/posts\/2023-06-14-ariadne\/pipeline_edit_poster.png\" style=\"max-width: 100%;\">\n        <source src=\"\/assets\/posts\/2023-06-14-ariadne\/pipeline_edit.mp4\" type=\"video\/mp4\" \/>\n        <p>\n            Your browser doesn't support HTML5 video. Here is a\n            <a href=\"\/assets\/posts\/2023-06-14-ariadne\/pipeline_edit.mp4\">link to the video<\/a> instead.\n        <\/p>\n  <\/video>\n    \n<figcaption style=\"margin-top: 0.5rem; text-align: center;\">\n    Search pipeline sandbox enables changes to the pipeline configuration and parameters, \n    and storing different configurations for later analysis.\n<\/figcaption>\n<\/figure>\n\n<p>Since launch, search has been undergoing active development. We often need to understand \nhow different versions of the search pipeline affect results. Running \u201cwhat if\u201d analyses \nwith different pipeline configurations, search queries, and test clients is essential for \nfinding the best path for improvement. After launch, we added a capability to Ariadne to \nsupport this work by making the components  of the search pipeline and their configurations \nfully modifiable. The modifications can be preserved in a lightweight store and shared with \ncollaborators using an encoded url, which also encodes the search query and test client id.<\/p>\n\n<p>Ariadne\u2019s capabilities, co-evolving with specialized needs of the Search team, have \nsupported development of personalized search at Stitch Fix beyond standard observability \ntools. Search is a highly collaborative and technically complex program, and its success \nrelies on speed of iterative improvement, flexibility of experimentation, and ease of \nsystem management. Investment in building Ariadne, a dedicated observability UI, has \namplified the work of the Search team by addressing these needs.<\/p>\n","pubDate":"Tue, 13 Jun 2023 01:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/06\/13\/ariadne-observability-ui-for-search\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/06\/13\/ariadne-observability-ui-for-search\/"},{"title":"Accelerating AI: Implementing Multi-GPU Distributed Training for Personalized Recommendations","description":"<p>Stitch Fix uses a cutting-edge multi-tiered recommender system stack to personalize styling recommendations at scale. This stack comprises several critical components, including feature generation, scoring, ranking, and inventory optimization techniques.<\/p>\n\n<p>Our scoring module is based on the <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/10\/14\/client-time-series-model\/\">Client Time Series Model<\/a> (CTSM) which is an <a href=\"https:\/\/www.modernretail.co\/wp-content\/uploads\/sites\/5\/2023\/02\/MODERN-RETAIL-AWARDS_Winners-Guide_020123.pdf\">award winning<\/a> novel sequence based model that uses temporally masked encoders. CTSM is built using <a href=\"https:\/\/pytorch.org\/\">PyTorch<\/a>, and was initially trained on a single Graphics Processing Unit (GPU) instance. Since we first put this model into production last year, we have launched several updates to the model that improved its performance. Many of these improvements involved adding new features or increasing the time window of our training data. As a result, the model training time increased significantly, making it harder for us to iterate quickly and get feedback on new ideas we want to try for improving the model. We needed a way to reduce the model training time.<\/p>\n\n<p>This blog delves into the steps we followed to overcome this challenge and our journey to implement multi-GPU distributed model training for CTSM. By sharding the training data across multiple GPUs and training multiple mini-batches in parallel, we aimed to achieve significant reductions in training time. We present empirical results showcasing the observed reduction in training time when we scaled up resources from 1 to N GPUs, and share some future directions we are considering in our continued effort to speed up model training.<\/p>\n\n<h2 id=\"model-training-workflow\">Model Training Workflow<\/h2>\n\n<p>The scores generated by CTSM are leveraged by multiple downstream services to get insight into what items a client is likely to purchase. The model is retrained at a regular cadence to ensure that it is using the most updated information about each client when making predictions and does not degrade in its performance. We leverage <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/08\/02\/configuration-driven-ml-pipelines\/\">configuration driven machine learning pipelines<\/a> to set up a Directed Acyclic Graph (DAG) that automatically retrains the model, checks if the model performance is above a set threshold, and deploys the new model in production. Below is a high level overview of the entire workflow:<\/p>\n\n<div style=\"text-align:center\">\n  <img src=\"\/assets\/posts\/2023-06-08-distributed-model-training\/ctsm_training_workflow.png\" width=\"100%\" title=\"CTSM Training Workflow\" alt=\"Diagram illustrating the training workflow of CTSM\" style=\"display: block; margin-bottom: 20px; margin-top: 20px;\" \/>\n<\/div>\n\n<h2 id=\"distributed-model-training-for-ctsm\">Distributed Model Training for CTSM<\/h2>\n\n<h3 id=\"pytorch-lightning-trainer\">Pytorch Lightning Trainer<\/h3>\n\n<p>As we worked on our effort to parallelize model training, we recognized the need to make an important design decision to ensure that our code was device-agnostic and scalable across multiple GPUs. Our goal was to minimize maintenance overhead for our team and keep our multi-processing code, which enables training on multiple GPUs, to a minimum. After considering various options, we ultimately chose to adopt the PyTorch Lightning framework for model training.<\/p>\n\n<p><a href=\"https:\/\/lightning.ai\/pages\/open-source\/\">PyTorch Lightning<\/a> is an open-source framework that provides a higher-level interface to PyTorch, making it easier to write code for training deep learning models. It includes built-in support for distributed model training using different strategies such as Data Parallel, Distributed Data Parallel, and more. By adopting this framework, we were able to reduce the amount of boilerplate training code we had to write and streamline the code for training CTSM on multiple GPUs.<\/p>\n\n<p>However, it\u2019s important to note that there are potential drawbacks to adopting this framework. For example, it requires your training code, such as the forward pass and optimization logic, to be structured in a specific way (in our case, we needed to refactor our code to adopt this framework for CTSM). It can also be challenging to customize the training loop or implement novel training strategies that are not already included in Lightning. However, we found that the benefits of using PyTorch Lightning outweighed these potential drawbacks  for our project. Ultimately, the decision to use PyTorch Lightning should be based on a careful evaluation of the specific use case, and the available resources and expertise.<\/p>\n\n<h3 id=\"data-parallel-dp-vs-distributed-data-parallel-ddp\">Data Parallel (DP) vs. Distributed Data Parallel (DDP)<\/h3>\n\n<p><a href=\"https:\/\/pytorch.org\/docs\/stable\/generated\/torch.nn.DataParallel.html\">Data Parallel<\/a> and <a href=\"https:\/\/pytorch.org\/docs\/stable\/generated\/torch.nn.parallel.DistributedDataParallel.html\">Distributed Data Parallel<\/a> are the two most commonly used strategies for distributed model training with data sharding. There are key differences between these two approaches that we discuss below. Both strategies use common elements such as a <a href=\"https:\/\/pytorch.org\/docs\/stable\/data.html#torch.utils.data.DataLoader\">data loader<\/a> that is responsible for generating mini-batches to train the model, and the <a href=\"https:\/\/pytorch.org\/docs\/stable\/generated\/torch.nn.Module.html\">model<\/a> itself with parameters to train using this training data.<\/p>\n\n<h4 id=\"data-parallel-dp\">Data Parallel (DP)<\/h4>\n\n<p>In the Data Parallel approach, the data loader and model are initialized as part of a base module, and we assume that we have N GPUs available for model training. During each training step, DP performs the following operations:<\/p>\n\n<ol>\n  <li>The mini-batch is split into N segments of roughly equal size, and each segment is copied over to its corresponding GPU.<\/li>\n  <li>The model object is replicated and copied over to each GPU.<\/li>\n  <li>Each GPU executes a forward pass using its chunk of the mini-batch and backpropagation to compute gradients.<\/li>\n  <li>These gradients are accumulated across all the GPUs and used to update the model object in the base module.<\/li>\n<\/ol>\n\n<p>These steps are repeated for training each mini-batch until a set stopping criterion, such as the maximum number of epochs to train on, is reached. Steps 1 and 2 are both copy operations, whereas step 4 is a synchronization operation that gathers gradients computed across all the GPUs for each parameter.<\/p>\n\n<p>Given below is a visual representation of steps executed by DP (steps in blue represent the operations performed during each training step)<\/p>\n\n<div style=\"text-align:center\">\n  <img src=\"\/assets\/posts\/2023-06-08-distributed-model-training\/data_parallel.png\" width=\"100%\" title=\"Data Parallel\" alt=\"Diagram illustrating the steps executed when using Data Parallel strategy for model training\" style=\"display: block; margin-bottom: 20px; margin-top: 20px;\" \/>\n<\/div>\n\n<h4 id=\"distributed-data-parallel-ddp\">Distributed Data Parallel (DDP)<\/h4>\n\n<p>DDP takes a slightly different approach. Similar to DP, the data loader and model are initialized as part of a base module, but it performs an additional step where it copies over the initialized model to each GPU. This model copy operation is only done once during initialization. DDP performs the following operations during each training step:<\/p>\n\n<ol>\n  <li>Generate N new mini-batches (one for each GPU), and copy over each mini-batch to its corresponding GPU.<\/li>\n  <li>Each GPU executes a forward pass on its own mini-batch and backpropagation to compute gradients.<\/li>\n  <li>These gradients are accumulated across all GPUs and averaged. The average gradients are broadcasted to all the GPUs.<\/li>\n  <li>Based on average gradients received, each GPU updates the parameters of its local copy of the model<\/li>\n<\/ol>\n\n<p>DDP is significantly faster than DP because it only has one data copy operation (step 1). Step 3 is a communication operation that waits for all GPUs to compute gradients for each parameter and broadcasts average gradients back to the GPUs. Step 4 ensures that the model object is identical across all GPUs as they all use the same set of average gradients to update their parameters<\/p>\n\n<p>Given below is a visual representation of the steps performed by DDP (steps in blue represent operations performed in each training step)<\/p>\n\n<div style=\"text-align:center\">\n  <img src=\"\/assets\/posts\/2023-06-08-distributed-model-training\/distributed_data_parallel.png\" width=\"100%\" title=\"Data Parallel\" alt=\"Diagram illustrating the steps executed when using Distributed Data Parallel strategy for model training\" style=\"display: block; margin-bottom: 20px; margin-top: 20px;\" \/>\n<\/div>\n\n<p>Based on our understanding of how DP and DDP parallelize model training, we expected DDP to be faster and more efficient for distributed model training. <a href=\"https:\/\/pytorch.org\/docs\/stable\/notes\/cuda.html#use-nn-parallel-distributeddataparallel-instead-of-multiprocessing-or-nn-dataparallel\">PyTorch documentation<\/a> also recommends using the DDP strategy over DP because DP uses multi-threading, which could suffer from performance issues due to Python\u2019s <a href=\"https:\/\/docs.python.org\/3\/glossary.html#term-global-interpreter-lock\">Global Interpreter Lock<\/a>, whereas DDP uses multi-processing, spawning a new process on each GPU.<\/p>\n\n<p>Therefore, we adopted the DDP strategy for training CTSM on multiple GPUs using the PyTorch Lightning trainer, as discussed above.<\/p>\n\n<h3 id=\"ddp-training-of-ctsm\">DDP training of CTSM<\/h3>\n\n<h4 id=\"executing-model-training-job-on-multiple-gpus\">Executing model training job on multiple GPUs<\/h4>\n\n<p>We use the <a href=\"https:\/\/github.com\/stitchfix\/flotilla-os\">Flotilla<\/a> framework to submit containerized jobs and execute CTSM training on our <a href=\"https:\/\/aws.amazon.com\/eks\/\">EKS<\/a> cluster. By specifying resource requests for CPU, memory, and number of GPUs required for training, this approach allows us to share an <a href=\"https:\/\/aws.amazon.com\/ec2\/\">EC2<\/a> instance that has multiple GPUs with other model training jobs. By doing so, we can make the most of each EC2 instance in the cluster, which leads to better utilization of resources and significant cost savings.<\/p>\n\n<p>To test the scalability of CTSM training with DDP, we tried training using 1 to 8 GPUs on a single <a href=\"https:\/\/instances.vantage.sh\/aws\/ec2\/g5.48xlarge\">g5.48xlarge<\/a> instance. As we increased the number of GPUs used, model training time per epoch went down as expected. The plot below shows average training time per epoch benchmarked against training time on 1 GPU (e.g. training time on 2 GPUs took 0.55 times that of training time on 1 GPU). When we compare these observed scaling factors with ideal scaling factors, we see that DDP does exceptionally well as parallelizing model training and comes very close to the ideal numbers as we scale up the number of GPUs used.<\/p>\n\n<div style=\"text-align:center\">\n  <img src=\"\/assets\/posts\/2023-06-08-distributed-model-training\/training_time_per_epoch.png\" width=\"100%\" title=\"Training Time per number of GPUs\" alt=\"Training time benchmarked against that on 1 GPU\" style=\"display: block; margin-bottom: 20px; margin-top: 20px;\" \/>\n<\/div>\n\n<p>As the number of GPUs utilized for training increases, the communication overhead within the DDP process also increases. This overhead arises due to the need to synchronize and accumulate gradients across all GPUs involved in the training process. The following plot illustrates the average time consumed by communication overhead in each epoch. For instance, when training CTSM on 2 GPUs, approximately 9% of the training time is dedicated to coordinating gradient computations between the 2 GPUs. However, this overhead amplifies significantly to nearly 23% when employing 8 GPUs, as the coordination across a larger number of GPUs becomes more time-consuming.<\/p>\n\n<div style=\"text-align:center\">\n  <img src=\"\/assets\/posts\/2023-06-08-distributed-model-training\/comms_overhead_dist.png\" width=\"100%\" title=\"Communication overhead per number of GPUs\" alt=\"Communication overhead represented as percentage of total training time per number of GPUs\" style=\"display: block; margin-bottom: 20px; margin-top: 20px;\" \/>\n<\/div>\n\n<p>Given that model training costs increase as the number of GPUs used for training increases, we carefully considered the number of GPUs we wanted to use. After weighing the trade-offs between training time and cost, we decided to train the model across 2 GPUs. This increased our training costs to ~2 times the cost of training on a single GPU, but it reduced the model training time to 0.55x that of the training time on a single GPU. We believe that this reduced training time will allow us to iterate faster and improve our key business metrics, which will outweigh the additional training costs incurred.<\/p>\n\n<h4 id=\"model-performance-monitoring\">Model performance monitoring<\/h4>\n\n<p>We use <a href=\"https:\/\/pytorch.org\/docs\/stable\/tensorboard.html\">tensorboard<\/a> utility within PyTorch for monitoring model performance, and the distribution of model weights and biases along with their gradients. The graphs below show a time-series distribution of loss computed per mini-batch for CTSM trained on 2 GPUs, with orange and blue colors representing separate GPUs. X-axis shows the number of training steps, while the y-axis shows the corresponding losses on training and validation data (shown as \u2018training_loss\u2019 and \u2018test_loss\u2019 respectively in the graphs below). Due to different mini-batches used by each GPU, there are slight variations in the exact loss values, but applying smoothing shows that both GPUs follow a similar trend where loss is reduced over time.<\/p>\n\n<div style=\"text-align:center\">\n  <img src=\"\/assets\/posts\/2023-06-08-distributed-model-training\/tensorboard_training_loss.png\" width=\"100%\" title=\"Training Loss\" alt=\"Plot showing the progress of loss on training data as we train the model on more epochs\" \/>\n<\/div>\n\n<div style=\"text-align:center\">\n  <img src=\"\/assets\/posts\/2023-06-08-distributed-model-training\/tensorboard_test_loss.png\" width=\"100%\" title=\"Test Loss\" alt=\"Plot showing the progress of loss on test data as we train the model on more epochs\" \/>\n<\/div>\n\n<h4 id=\"productionizing-the-model\">Productionizing the model<\/h4>\n\n<p>We use a backtesting process to assess CTSM performance on a held-out validation dataset. When we refactored CTSM to use DDP, we observed a slight drop in backtesting performance due to a change in the effective batch size. In particular, when training with one GPU, we called the optimizer to update weights and biases after each mini-batch. But with two GPUs using DDP, we use average gradients across two mini-batches to update weights and bases. Hence, the optimizer is only called once per two mini-batches, which effectively doubles the batch size used for training. As batch size is an important hyper parameter that requires careful tuning, this change negatively impacted the model performance.<\/p>\n\n<p>To address this, we conducted an exercise of hyperparameter optimization and tweaked the learning rate scheduler to enhance model performance. Ultimately, we trained the model using DDP on 2 GPUs, with new hyperparameters, and verified using backtesting that this change did not negatively impact the model performance. We then launched a do-no-harm online experiment that further tested the hypothesis that this change did not negatively impact any of our business metrics. This experiment was successful and we launched this model in production for all our traffic earlier this year.<\/p>\n\n<h2 id=\"learnings-and-next-steps\">Learnings and Next Steps<\/h2>\n\n<p>Clear design requirements, particularly the ability to scale up training across more GPUs while reducing maintenance overhead on the team, have already paid off. We recently launched an experiment that requires training the model on significantly more data. Our design enabled us to easily scale up training from 2 to 4 GPUs with minimal code changes.<\/p>\n\n<p>While we\u2019ve only utilized multiple GPUs on a single physical instance so far, we recognize that DDP can also parallelize training across multiple physical instances, which would require setting up a GPU cluster or additional infrastructure provisioning. We plan to explore this option in the future as we increase our training data and potentially require parallelization beyond a single EC2 instance.<\/p>\n\n<p>Currently, we\u2019re using PyTorch 1.x, but we\u2019re considering migrating to PyTorch 2.0 to <a href=\"https:\/\/pytorch.org\/get-started\/pytorch-2.0\/#pytorch-2x-faster-more-pythonic-and-as-dynamic-as-ever\">pre-compile<\/a> the model graph before training. While this has the potential to reduce training time, early experiments with PyTorch 2.0 have shown mixed results in terms of potential speedup for our training jobs. This is because pre-compiling the graph prevents DDP from applying optimizations in its communication step that make it exceptionally fast. This issue is explained in detail in this <a href=\"https:\/\/dev-discuss.pytorch.org\/t\/torchdynamo-update-9-making-ddp-work-with-torchdynamo\/860\">informative blog<\/a>.<\/p>\n\n<p>Additionally, we\u2019re exploring the use of <a href=\"https:\/\/pytorch.org\/docs\/stable\/amp.html\">automatic mixed precision<\/a> to switch to float16 precision wherever possible without degrading model performance (e.g. fully connected layers)<\/p>\n\n<p>Overall, we\u2019ll continue to explore various techniques to speed up model training as we increase our training data or network complexity. This will also allow us to maintain our developer velocity, retrain the model at a regular cadence, and ensure that we are using the most updated model artifact for making personalized recommendations to our customers.<\/p>\n","pubDate":"Thu, 08 Jun 2023 09:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/06\/08\/distributed-model-training\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/06\/08\/distributed-model-training\/"},{"title":"A New Era of Creativity: Expert-in-the-loop Generative AI at Stitch Fix","description":"<p>Generative AI has been gaining attention and popularity in recent years. Made possible with advances in deep learning algorithms and trained with previously unimaginable amounts of data, generative AI has already contributed many real-world use cases, from creating realistic images with systems like DALL-E 2 and Midjourney, to generating human-like responses with ChatGPT.<\/p>\n\n<p>At Stitch Fix, we are constantly exploring innovative ways to utilize the latest <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/07\/19\/your-opinion-matters\/\">advancements<\/a> in AI and ML to enhance the experiences of our clients. In this blog post, we will delve into our approach to generative AI, with a special focus on our text generation use cases. By combining algo-generated text with a human expert-in-the-loop approach, we aim to streamline tasks  such as crafting engaging advertisement headlines and producing high-fidelity product descriptions.<\/p>\n\n<h2 id=\"algo-generated-ad-headlines\">Algo-generated Ad Headlines<\/h2>\n<p>Generative AI in the text space is powered by large language models (LLMs) that are pre-trained on vast amounts of data (for example, GPT-3 is pre-trained on nearly the entire internet) and can understand and generate natural language. However, once pre-trained, it can generalize from very limited amounts of data and is capable of performing a wide variety of natural language tasks such as Q&amp;A, translation, summarization, and text generation. This few-shot learning capability, which relies only on a few examples to make predictions, makes it especially well suited for tasks that require creativity and originality, such as crafting compelling ad headlines.<\/p>\n\n<p>Ad headlines are often the first interaction with potential clients, so it\u2019s crucial to make them engaging. Traditional marketing requires a copywriter to write new headlines for every new ad asset, which can be time consuming and costly, and may not always result in unique copy. Using generative AI, such as GPT-3, we can quickly generate a large number of headlines tailored to our brand tone and messaging.<\/p>\n\n<p>We achieve this by using a combination of latent style understanding (check out <a href=\"https:\/\/newsroom.stitchfix.com\/blog\/how-we-understand-your-personal-style\/\">this blog<\/a> and <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2018\/06\/28\/latent-style\/\">this blog<\/a> to learn more about how we understand clients\u2019 personal styles), word embeddings (read more about word embeddings in <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2015\/03\/11\/word-is-worth-a-thousand-vectors\/\">this blog<\/a> and <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2019\/07\/15\/give-me-jeans\/\">this blog<\/a>), and few-shot learning. \nOur ad assets primarily consist of many outfit images that illustrate a wide range of styles we offer. First, we map the outfit and a set of style keywords (such as effortless, classic, romantic, professional, boho etc.) to the latent style space, and then find the style keywords closest to the outfit in that space. Next, we use GPT-3 to generate headlines based on the selected style keywords. Our human experts (copywriters) then review and edit the headlines generated by AI to ensure they capture the style of the outfit and align with the brand\u2019s tone and messaging. This human expert-in-the-loop approach allows us to leverage the creativity and efficiency of generative AI while still maintaining human oversight. For our copywriters, reviewing headlines instead of writing new ones saves a significant amount of time and effort.<\/p>\n\n<div style=\"text-align:center\">\n  <img src=\"\/assets\/posts\/2023-03-06-expert-in-the-loop-generative-ai-at-stitch-fix\/autotitle_diagram.png\" width=\"100%\" title=\"Algo-generated Ad Headline diagram\" alt=\"Diagram illustrating how we generate ad headlines\" \/>\n<\/div>\n\n<p>We have since used the expert-in-the-loop approach for generating all ad headlines for Facebook and Instagram campaigns, and have continued to benefit from improved efficiency while not sacrificing quality. Additionally, we\u2019ve been constantly seeking opportunities to extend this capability to other areas.<\/p>\n\n<h2 id=\"algo-generated-product-descriptions\">Algo-generated Product Descriptions<\/h2>\n<blockquote class=\"abstract\">\n<p> \n\u201cA smart choice for everyday wear, this crew neck T-shirt is a versatile addition to your wardrobe, pairing well with jeans, leggings and shorts.\u201d\n<\/p>\n<\/blockquote>\n\n<p>With the success of algo-generated ad headlines, we have gained confidence in the potential of expert-in-the-loop generative AI for production use cases. Next, we set our sights on a problem of even greater scale and complexity: product descriptions.<\/p>\n\n<p>Product descriptions play a crucial role in e-commerce and fashion retail websites. Well-written, accurate, and detailed descriptions can enhance the client experience, build trust, and improve search engine optimization. Our Freestyle offering, where clients can shop for individual items in their own personal shopping feed, benefits greatly from informative and compelling product descriptions on the product detail pages (PDP).  Writing descriptions for hundreds of thousands of styles in inventory is a daunting task for human copywriters alone, and relying on the few-shot learning approach used for ad headlines results in generic, limited quality descriptions. We needed a solution that could build on the generic large language model with few-shot learning and utilize expert-written examples to create a customized solution for our use case.<\/p>\n\n<p>Enter, fine-tuning!<\/p>\n\n<p>Fine-tuning is the process of retraining a pre-trained base model on a smaller, task-specific dataset in order to adapt it to a specific use case. Through fine-tuning, the model learns the unique language, style, and requirements of the specific task, leading to improved performance compared to a generic pre-trained model. For our product description use case, we gathered a task-specific dataset by having our human experts write several hundred high-quality product descriptions (the \u201ccompletion\u201d, or training output) based on product attributes (the \u201cprompt\u201d, or training input). We then fine-tuned the base model on this task-specific dataset to teach the model our language, style, and template for high-quality product descriptions. This resulted in accurate and engaging descriptions tailored to meet the needs of our clients, all written in the Stitch Fix brand voice.<\/p>\n\n<p>Our fine-tuned algo solution offers unbeatable time savings as well as excellent scalability without sacrificing quality of descriptions. In fact, in a blind evaluation, where we compared our algo-generated product descriptions with written descriptions, we found that the descriptions generated by our AI solution achieved higher quality scores, which demonstrated the efficacy of our fine-tuned algorithm solution.<\/p>\n\n<h2 id=\"an-expert-in-the-loop-approach\">An Expert-in-the-loop Approach<\/h2>\n<p>In both use cases above, we used an \u201cexpert-in-the-loop\u201d approach that incorporates human expertise into the text generation and evaluation process. It combines the efficiency and scalability of algorithmic solutions with the quality and expertise of human experts. The result is a solution that not only delivers high-quality content but also continuously improves with each iteration.<\/p>\n\n<p>In comparison to relying solely on human experts, the expert-in-the-loop approach is much more efficient and fun. Our copywriters have reported saving significant time and effort as they review and edit the algo-generated content instead of writing new content from scratch. They have also shared that the algo-generated content can be fun and even inspiring to work with, as there are often interesting expressions or angles that are not typical of human-generated content.<\/p>\n\n<p>Compared to purely algorithmic solutions, the expert-in-the-loop approach ensures the quality and appropriateness of the client-facing content. Among all generative AI applications, text generation may be the area where human expertise is needed most. Natural language is  complex and nuanced, and while algorithms are able to generate text, they often fall short when it comes to capturing the subtleties of human language such as tone and sentiment. That\u2019s where human experts come in. Only human experts are able to distinguish between these nuances and choose the best expressions for the algorithm to model after.<\/p>\n\n<p>In our expert-in-the-loop approach, human experts work with us from the very beginning to define what a high-quality output should look like. For product descriptions, for example, the output should be original, unique, and sound natural and compelling. It should also make truthful statements about the product and align with our brand guidelines. As we iterate and improve the algorithm, our experts provide valuable insight into how to further improve the solution. For example, in ad headlines, our copywriters can discern if certain fashion-forward wording may not align with our brand messaging. This intelligence can help us further fine-tune the algorithm and improve the quality of the output through regular quality assurance checks. The expert-in-the-loop approach thus creates a positive feedback loop where human experts and algorithms work together to continually improve the quality of the generated content.<\/p>\n\n<p>As we look ahead and as the use of generative AI continues to grow and evolve, we are excited to explore the potential of generative AI in even more use cases across our business: assisting efficient styling, textual expression of style understanding, and much more.<\/p>\n\n","pubDate":"Mon, 06 Mar 2023 09:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/03\/06\/expert-in-the-loop-generative-ai-at-stitch-fix\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/03\/06\/expert-in-the-loop-generative-ai-at-stitch-fix\/"},{"title":"Polymorphic, Recursive Interfaces Using Go Generics","description":"<p>I did a bit of experimenting over the weekend in an attempt to\nfigure out how to write an interface that abstracted over methods whose\nreturn type was identical to the receiver\u2019s type. This is frequently\na thing that one wants to do when abstracting over self-cloning\nobjects, or things that implement the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Builder_pattern\">Builder pattern<\/a>.<\/p>\n\n<p>For example, suppose we have a struct through which we log stuff:<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">type<\/span> <span class=\"n\">StdoutLogger<\/span> <span class=\"k\">struct<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">out<\/span>    <span class=\"n\">ioutil<\/span><span class=\"o\">.<\/span><span class=\"n\">Writer<\/span>\n\t<span class=\"n\">outMu<\/span>  <span class=\"n\">sync<\/span><span class=\"o\">.<\/span><span class=\"n\">Mutex<\/span>\n\t<span class=\"n\">fields<\/span> <span class=\"k\">map<\/span><span class=\"p\">[<\/span><span class=\"kt\">string<\/span><span class=\"p\">]<\/span><span class=\"k\">interface<\/span><span class=\"p\">{}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">func<\/span> <span class=\"p\">(<\/span><span class=\"n\">n<\/span> <span class=\"o\">*<\/span><span class=\"n\">StdoutLogger<\/span><span class=\"p\">)<\/span> <span class=\"n\">WithFields<\/span><span class=\"p\">(<\/span><span class=\"n\">fields<\/span> <span class=\"k\">map<\/span><span class=\"p\">[<\/span><span class=\"kt\">string<\/span><span class=\"p\">]<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span> <span class=\"p\">(<\/span><span class=\"n\">out<\/span> <span class=\"o\">*<\/span><span class=\"n\">StdoutLogger<\/span><span class=\"p\">)<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"k\">for<\/span> <span class=\"n\">k<\/span><span class=\"p\">,<\/span> <span class=\"n\">v<\/span> <span class=\"o\">:=<\/span> <span class=\"k\">range<\/span> <span class=\"n\">fields<\/span> <span class=\"p\">{<\/span>\n\t\t<span class=\"n\">out<\/span><span class=\"o\">.<\/span><span class=\"n\">fields<\/span><span class=\"p\">[<\/span><span class=\"n\">k<\/span><span class=\"p\">]<\/span> <span class=\"o\">=<\/span> <span class=\"n\">v<\/span>\n\t<span class=\"p\">}<\/span>\n\n\t<span class=\"k\">return<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">func<\/span> <span class=\"p\">(<\/span><span class=\"n\">n<\/span> <span class=\"o\">*<\/span><span class=\"n\">StdoutLogger<\/span><span class=\"p\">)<\/span> <span class=\"n\">Infof<\/span><span class=\"p\">(<\/span><span class=\"n\">format<\/span> <span class=\"kt\">string<\/span><span class=\"p\">,<\/span> <span class=\"n\">args<\/span> <span class=\"o\">...<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">n<\/span><span class=\"o\">.<\/span><span class=\"n\">outMu<\/span><span class=\"o\">.<\/span><span class=\"n\">Lock<\/span><span class=\"p\">()<\/span>\n\t<span class=\"k\">defer<\/span> <span class=\"n\">n<\/span><span class=\"o\">.<\/span><span class=\"n\">outMu<\/span><span class=\"o\">.<\/span><span class=\"n\">Unlock<\/span><span class=\"p\">()<\/span>\n\n\t<span class=\"n\">s<\/span> <span class=\"o\">:=<\/span> <span class=\"n\">fmt<\/span><span class=\"o\">.<\/span><span class=\"n\">Sprintf<\/span><span class=\"p\">(<\/span><span class=\"n\">format<\/span><span class=\"p\">,<\/span> <span class=\"n\">args<\/span><span class=\"o\">...<\/span><span class=\"p\">)<\/span>\n\n\t<span class=\"k\">if<\/span> <span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">n<\/span><span class=\"o\">.<\/span><span class=\"n\">fields<\/span><span class=\"p\">)<\/span> <span class=\"o\">&gt;<\/span> <span class=\"m\">0<\/span> <span class=\"p\">{<\/span>\n\t\t<span class=\"n\">s<\/span> <span class=\"o\">+=<\/span> <span class=\"s\">\" \"<\/span>\n\t<span class=\"p\">}<\/span>\n\n\t<span class=\"k\">for<\/span> <span class=\"n\">k<\/span><span class=\"p\">,<\/span> <span class=\"n\">v<\/span> <span class=\"o\">:=<\/span> <span class=\"k\">range<\/span> <span class=\"n\">n<\/span><span class=\"o\">.<\/span><span class=\"n\">fields<\/span> <span class=\"p\">{<\/span>\n\t\t<span class=\"n\">s<\/span> <span class=\"o\">+=<\/span> <span class=\"n\">fmt<\/span><span class=\"o\">.<\/span><span class=\"n\">Sprintf<\/span><span class=\"p\">(<\/span><span class=\"s\">\"%s=%+v\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">k<\/span><span class=\"p\">,<\/span> <span class=\"n\">v<\/span><span class=\"p\">)<\/span>\n\t<span class=\"p\">}<\/span>\n\n\t<span class=\"n\">n<\/span><span class=\"o\">.<\/span><span class=\"n\">out<\/span><span class=\"o\">.<\/span><span class=\"n\">Write<\/span><span class=\"p\">([]<\/span><span class=\"kt\">byte<\/span><span class=\"p\">(<\/span><span class=\"n\">s<\/span><span class=\"p\">))<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>\u2026and we\u2019ve got some other struct that we use during test which\nignores all requests to log stuff:<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">type<\/span> <span class=\"n\">NoopLogger<\/span> <span class=\"k\">struct<\/span> <span class=\"p\">{}<\/span>\n\n<span class=\"k\">func<\/span> <span class=\"p\">(<\/span><span class=\"n\">n<\/span> <span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">)<\/span> <span class=\"n\">WithFields<\/span><span class=\"p\">(<\/span><span class=\"n\">fields<\/span> <span class=\"k\">map<\/span><span class=\"p\">[<\/span><span class=\"kt\">string<\/span><span class=\"p\">]<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span> <span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"k\">return<\/span> <span class=\"n\">n<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">func<\/span> <span class=\"p\">(<\/span><span class=\"n\">n<\/span> <span class=\"n\">NoopLogger<\/span><span class=\"p\">)<\/span> <span class=\"n\">Infof<\/span><span class=\"p\">(<\/span><span class=\"n\">format<\/span> <span class=\"kt\">string<\/span><span class=\"p\">,<\/span> <span class=\"n\">args<\/span> <span class=\"o\">...<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"k\">return<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<h2 id=\"before-go-generics\">Before Go Generics<\/h2>\n\n<p>Before the Go \u201cgenerics\u201d feature was released, defining an interface\nthat abstracted over both structs was not possible (<a href=\"https:\/\/tip.golang.org\/doc\/go1.17_spec#Interface_types\">link<\/a>). For\nexample, if we had a pre-generics interface that looked like:<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">type<\/span> <span class=\"n\">Logger<\/span> <span class=\"k\">interface<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">WithFields<\/span><span class=\"p\">(<\/span><span class=\"n\">fields<\/span> <span class=\"k\">map<\/span><span class=\"p\">[<\/span><span class=\"kt\">string<\/span><span class=\"p\">]<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span> <span class=\"n\">Logger<\/span>\n\t<span class=\"n\">Infof<\/span><span class=\"p\">(<\/span><span class=\"n\">format<\/span> <span class=\"kt\">string<\/span><span class=\"p\">,<\/span> <span class=\"n\">args<\/span> <span class=\"o\">...<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>\u2026there would be no way to satisfy it with types that had these\nsignatures:<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">func<\/span> <span class=\"p\">(<\/span><span class=\"n\">n<\/span> <span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">)<\/span> <span class=\"n\">WithFields<\/span><span class=\"p\">(<\/span><span class=\"n\">fields<\/span> <span class=\"k\">map<\/span><span class=\"p\">[<\/span><span class=\"kt\">string<\/span><span class=\"p\">]<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span> <span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span>\n<span class=\"k\">func<\/span> <span class=\"p\">(<\/span><span class=\"n\">n<\/span> <span class=\"o\">*<\/span><span class=\"n\">StdoutLogger<\/span><span class=\"p\">)<\/span> <span class=\"n\">WithFields<\/span><span class=\"p\">(<\/span><span class=\"n\">fields<\/span> <span class=\"k\">map<\/span><span class=\"p\">[<\/span><span class=\"kt\">string<\/span><span class=\"p\">]<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span> <span class=\"o\">*<\/span><span class=\"n\">StdoutLogger<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>\u2026because of the different return types of each struct\u2019s\n<code class=\"language-plaintext highlighter-rouge\">WithFields<\/code> method.<\/p>\n\n<h2 id=\"polymorphic-interfaces\">Polymorphic Interfaces<\/h2>\n\n<p>Now that generics have landed, we <em>can<\/em> define an interface that\nabstracts over both of these structs:<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">type<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span> <span class=\"n\">any<\/span><span class=\"p\">]<\/span> <span class=\"k\">interface<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">WithFields<\/span><span class=\"p\">(<\/span><span class=\"n\">fields<\/span> <span class=\"k\">map<\/span><span class=\"p\">[<\/span><span class=\"kt\">string<\/span><span class=\"p\">]<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span> <span class=\"n\">T<\/span>\n\t<span class=\"n\">Infof<\/span><span class=\"p\">(<\/span><span class=\"n\">format<\/span> <span class=\"kt\">string<\/span><span class=\"p\">,<\/span> <span class=\"n\">args<\/span> <span class=\"o\">...<\/span><span class=\"k\">interface<\/span><span class=\"p\">{})<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">var<\/span> <span class=\"n\">x<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">]<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">new<\/span><span class=\"p\">(<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">var<\/span> <span class=\"n\">y<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"o\">*<\/span><span class=\"n\">StdoutLogger<\/span><span class=\"p\">]<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">new<\/span><span class=\"p\">(<\/span><span class=\"n\">StdoutLogger<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>Using that interface involves using generic \u201cconstraints\u201d\n(<a href=\"https:\/\/go.dev\/blog\/intro-generics\">link<\/a>), like so:<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">type<\/span> <span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]]<\/span> <span class=\"k\">struct<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">username<\/span> <span class=\"kt\">string<\/span>\n\t<span class=\"n\">password<\/span> <span class=\"kt\">string<\/span>\n\t<span class=\"n\">logger<\/span>   <span class=\"n\">T<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>What we\u2019re expressing with this <code class=\"language-plaintext highlighter-rouge\">Config<\/code> struct is that the struct\nowns a logger of type <code class=\"language-plaintext highlighter-rouge\">T<\/code>, where <code class=\"language-plaintext highlighter-rouge\">T<\/code> is constrained to any type\nwhich satisfies the <code class=\"language-plaintext highlighter-rouge\">Logger<\/code> interface (which itself is\npolymorphic).<\/p>\n\n<h2 id=\"weak-type-inference\">Weak Type Inference<\/h2>\n\n<p>While it is certainly cool that we can now define these sorts of\npolymorphic interfaces, Go\u2019s type inference is so weak as to make\nuse of those interfaces quite awkward. In my experiments, I\nfrequently found it to be the case that I needed to explicitly set a\ntype variable in a place where I would expect it to be inferred.<\/p>\n\n<p>Suppose for a moment that we export a bunch of config-manipulating\nfunctions, and that one of those functions can be used to configure\nout application to use a logger of some type that the user provides.<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"c\">\/\/ Config is a struct which holds our application's configuration.<\/span>\n<span class=\"k\">type<\/span> <span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]]<\/span> <span class=\"k\">struct<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">username<\/span> <span class=\"kt\">string<\/span>\n\t<span class=\"n\">password<\/span> <span class=\"kt\">string<\/span>\n\t<span class=\"n\">logger<\/span>   <span class=\"n\">T<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c\">\/\/ WithUsername configures the system to use the provided username.<\/span>\n<span class=\"k\">func<\/span> <span class=\"n\">WithUsername<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]](<\/span><span class=\"n\">username<\/span> <span class=\"kt\">string<\/span><span class=\"p\">)<\/span> <span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">config<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">])<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"k\">return<\/span> <span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">p<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">])<\/span> <span class=\"p\">{<\/span>\n\t\t<span class=\"n\">p<\/span><span class=\"o\">.<\/span><span class=\"n\">username<\/span> <span class=\"o\">=<\/span> <span class=\"n\">username<\/span>\n\t<span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c\">\/\/ WithPassword configures the system to use the provided password.<\/span>\n<span class=\"k\">func<\/span> <span class=\"n\">WithPassword<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]](<\/span><span class=\"n\">password<\/span> <span class=\"kt\">string<\/span><span class=\"p\">)<\/span> <span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">config<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">])<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"k\">return<\/span> <span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">p<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">])<\/span> <span class=\"p\">{<\/span>\n\t\t<span class=\"n\">p<\/span><span class=\"o\">.<\/span><span class=\"n\">password<\/span> <span class=\"o\">=<\/span> <span class=\"n\">password<\/span>\n\t<span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c\">\/\/ WithLogger configures the system to use the provided logger.<\/span>\n<span class=\"k\">func<\/span> <span class=\"n\">WithLogger<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]](<\/span><span class=\"n\">logger<\/span> <span class=\"n\">T<\/span><span class=\"p\">)<\/span> <span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">config<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">])<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"k\">return<\/span> <span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">p<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">])<\/span> <span class=\"p\">{<\/span>\n\t\t<span class=\"n\">p<\/span><span class=\"o\">.<\/span><span class=\"n\">logger<\/span> <span class=\"o\">=<\/span> <span class=\"n\">logger<\/span>\n\t<span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c\">\/\/ NewConfig creates a new configuring from the provided options.<\/span>\n<span class=\"k\">func<\/span> <span class=\"n\">NewConfig<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span> <span class=\"n\">Logger<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]](<\/span><span class=\"n\">opts<\/span> <span class=\"o\">...<\/span><span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">config<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]))<\/span> <span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">cfg<\/span> <span class=\"o\">:=<\/span> <span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"n\">T<\/span><span class=\"p\">]{}<\/span>\n\n\t<span class=\"k\">for<\/span> <span class=\"n\">_<\/span><span class=\"p\">,<\/span> <span class=\"n\">opt<\/span> <span class=\"o\">:=<\/span> <span class=\"k\">range<\/span> <span class=\"n\">opts<\/span> <span class=\"p\">{<\/span>\n\t\t<span class=\"n\">opt<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">cfg<\/span><span class=\"p\">)<\/span>\n\t<span class=\"p\">}<\/span>\n\n\t<span class=\"k\">return<\/span> <span class=\"n\">cfg<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>Suppose we wanted to construct a configuration that used our\n<code class=\"language-plaintext highlighter-rouge\">NoopLogger<\/code>. In many other languages, we\u2019d load all of our\nconfiguration functions into a monomorphized (i.e. non-polymorphic)\nslice, and then we\u2019d pass that slice around:<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">func<\/span> <span class=\"n\">main<\/span><span class=\"p\">()<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">opts<\/span> <span class=\"o\">:=<\/span> <span class=\"p\">[]<\/span><span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">config<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">]){<\/span>\n\t\t<span class=\"n\">WithUsername<\/span><span class=\"p\">(<\/span><span class=\"s\">\"foo\"<\/span><span class=\"p\">),<\/span>\n\t\t<span class=\"n\">WithPassword<\/span><span class=\"p\">(<\/span><span class=\"s\">\"bar\"<\/span><span class=\"p\">),<\/span>\n\t\t<span class=\"n\">WithLogger<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">{}),<\/span>\n\t<span class=\"p\">}<\/span>\n\n\t<span class=\"n\">cfg<\/span> <span class=\"o\">:=<\/span> <span class=\"n\">NewConfig<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"o\">...<\/span><span class=\"p\">)<\/span>\n\n\t<span class=\"n\">fmt<\/span><span class=\"o\">.<\/span><span class=\"n\">Printf<\/span><span class=\"p\">(<\/span><span class=\"s\">\"cfg is: %+v<\/span><span class=\"se\">\\n<\/span><span class=\"s\">\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">cfg<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>Unfortunately, Go\u2019s type inference is not able to infer that <code class=\"language-plaintext highlighter-rouge\">T<\/code> is\n<code class=\"language-plaintext highlighter-rouge\">*NoopLogger<\/code> for the <code class=\"language-plaintext highlighter-rouge\">WithUsername<\/code> and <code class=\"language-plaintext highlighter-rouge\">WithPassword<\/code> functions,\nin spite of the fact that <code class=\"language-plaintext highlighter-rouge\">opts<\/code> is not polymorphic.<\/p>\n\n<p>If you try to run this code, you\u2019ll see something like (<a href=\"https:\/\/go.dev\/play\/p\/sdb9qGPV7GI\">link<\/a>):<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"o\">.\/<\/span><span class=\"n\">prog<\/span><span class=\"o\">.<\/span><span class=\"k\">go<\/span><span class=\"o\">:<\/span><span class=\"m\">70<\/span><span class=\"o\">:<\/span><span class=\"m\">15<\/span><span class=\"o\">:<\/span> <span class=\"n\">cannot<\/span> <span class=\"n\">infer<\/span> <span class=\"n\">T<\/span> <span class=\"p\">(<\/span><span class=\"n\">prog<\/span><span class=\"o\">.<\/span><span class=\"k\">go<\/span><span class=\"o\">:<\/span><span class=\"m\">33<\/span><span class=\"o\">:<\/span><span class=\"m\">19<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">.\/<\/span><span class=\"n\">prog<\/span><span class=\"o\">.<\/span><span class=\"k\">go<\/span><span class=\"o\">:<\/span><span class=\"m\">71<\/span><span class=\"o\">:<\/span><span class=\"m\">15<\/span><span class=\"o\">:<\/span> <span class=\"n\">cannot<\/span> <span class=\"n\">infer<\/span> <span class=\"n\">T<\/span> <span class=\"p\">(<\/span><span class=\"n\">prog<\/span><span class=\"o\">.<\/span><span class=\"k\">go<\/span><span class=\"o\">:<\/span><span class=\"m\">40<\/span><span class=\"o\">:<\/span><span class=\"m\">19<\/span><span class=\"p\">)<\/span>\n\n<span class=\"n\">Go<\/span> <span class=\"n\">build<\/span> <span class=\"n\">failed<\/span><span class=\"o\">.<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>To work around the lack of type inference, you\u2019ll need to explicitly\nparameterize each function, like so:<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">func<\/span> <span class=\"n\">main<\/span><span class=\"p\">()<\/span> <span class=\"p\">{<\/span>\n\t<span class=\"n\">opts<\/span> <span class=\"o\">:=<\/span> <span class=\"p\">[]<\/span><span class=\"k\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">config<\/span> <span class=\"o\">*<\/span><span class=\"n\">Config<\/span><span class=\"p\">[<\/span><span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">]){<\/span>\n\t\t<span class=\"n\">WithUsername<\/span><span class=\"p\">[<\/span><span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">](<\/span><span class=\"s\">\"foo\"<\/span><span class=\"p\">),<\/span>\n\t\t<span class=\"n\">WithPassword<\/span><span class=\"p\">[<\/span><span class=\"o\">*<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">](<\/span><span class=\"s\">\"bar\"<\/span><span class=\"p\">),<\/span>\n\t\t<span class=\"n\">WithLogger<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">NoopLogger<\/span><span class=\"p\">{}),<\/span>\n\t<span class=\"p\">}<\/span>\n\n\t<span class=\"n\">cfg<\/span> <span class=\"o\">:=<\/span> <span class=\"n\">NewConfig<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"o\">...<\/span><span class=\"p\">)<\/span>\n\n\t<span class=\"n\">fmt<\/span><span class=\"o\">.<\/span><span class=\"n\">Printf<\/span><span class=\"p\">(<\/span><span class=\"s\">\"cfg is: %+v<\/span><span class=\"se\">\\n<\/span><span class=\"s\">\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">cfg<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>Not particularly awesome.<\/p>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n\n<p>Go\u2019s generics implementation allows us to solve some problems that\nwere previously difficult or impossible to solve, but the inference\nalgorithm is such that explicit parameterization is required in\nplaces where one would expect types to be inferred, which can be\nquite awkward.<\/p>\n\n","pubDate":"Wed, 01 Feb 2023 09:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/02\/01\/go-polymorphic-interfaces\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/02\/01\/go-polymorphic-interfaces\/"},{"title":"2022 Intern Projects","description":"<p>Earlier this year, we had four fantastic interns join our Algorithms team for 3 months to learn how we harness data science in our work at Stitch Fix. These four interns hail from across the country and spent their time exploring a specific project and advancing their skills in their unique interest areas. In their own words below, they\u2019ve showcased each of their own projects and the meaningful insights they were able to uncover in their short time with us.<\/p>\n\n<hr \/>\n<h3 id=\"optimizing-inventory-allocation-for-client-facing-search\">Optimizing inventory allocation for client-facing search<\/h3>\n<p style=\"font-size:1rem\"><i>Maria Olaru, PhD candidate in Computational Neuroscience at University of California - San Francisco<\/i><\/p>\n\n<p>In an effort to expand beyond its core business of Fixes, a service where stylists select five personalized items and send them straight to clients\u2019 doors, Stitch Fix launched Freestyle. Freestyle is a personalized and instantly shoppable feed of items that clients can directly buy outside of their Fix. Within Freestyle, Stitch Fix recently launched a Search feature, allowing clients to directly query personalized items. I spent my time at Stitch Fix investigating how to optimize Stitch Fix\u2019s existing inventory allocation to better serve customers who use Search within Freestyle to search for products. For my project, I chose inventory-related metrics to explore, collected the corresponding data, and compared these metrics to client satisfaction.<\/p>\n\n<p>I chose inventory-related metrics that I could compare to client satisfaction: personalization and relevance. Personalization captures how well our items reflect clients\u2019 individual style, while relevance captures accurately our items reflect what a client asked for. With Fix orders, we view personalization as a top metric that predicts client purchases. However, Freestyle  differs from Fix in a crucial manner: clients using Fix are not asking for a specific item, whereas clients using Search within Freestyle know what they want, and are explicitly looking for it.<\/p>\n\n<p>Next, I collected data for these metrics. To explore personalization and relevance in our archive of search queries, I built a search pipeline component that allows us to capture these metrics. However, relevance metrics are normalized within a single query, not across multiple queries. To compare relevance metrics across queries in a way that takes inventory fluctuations into account, I normalized the relevance of each query with respect to inventory availability.<\/p>\n\n<p>Now that I had all the data I needed, I compared these metrics to client satisfaction. Using the observationally collected data, I found differing trends in how normalized relevance and personalization relate to client satisfaction. That being said, my findings may be confounded by when the customer searched for an item, or what  the customer asked for. To investigate whether allocating existing inventory to optimize for these trends directly increases client satisfaction, stakeholders across the Algorithms and Product organizations are collaborating on an experimental proposal \u2013 stay tuned to see what they find!<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <img alt=\"xxx\" src=\"\/assets\/posts\/2022-12-12-internship\/olaru_plot.png\" width=\"100%\" \/>\n\n  <figcaption style=\"text-align:center\"><i>\n This figure is illustrative. Observing how inventory metrics may relate to client satisfaction informs experimental intervention strategies.<\/i><\/figcaption>\n<\/figure>\n\n<hr \/>\n<h3 id=\"network-flow-optimization-for-freestyle-client-product-matching\">Network Flow Optimization for Freestyle Client-Product Matching<\/h3>\n<p style=\"font-size:1rem\"><i>Eric O\u2019Neill PhD student in Chemical and Biological Engineering at Princeton University<\/i><\/p>\n\n<p>I had the opportunity to work with the very talented Global Optimization team on a project related to inventory targeting for Freestyle. To make sure our items are seen by the people to whom they matter the most, and to provide an excellent personalized shopping experience, we solve a variation of the classic assignment problem. Solving the assignment problem seeks to make an optimal set of decisions that assign products to clients based on their corresponding \u2018match score\u2019: a cutting-edge internal prediction of how likely a client is to purchase an item if we show it to them. The assignment decisions are also subject to constraints on the number of items each client sees and inventory constraints to ensure we don\u2019t over-assign items.<\/p>\n\n<p>We can formulate and solve the assignment problem as a standard integer program (IP):<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <img alt=\"xxx\" src=\"\/assets\/posts\/2022-12-12-internship\/oneill_equation.png\" width=\"100%\" \/>\n<\/figure>\n\n<p>Where <em>x<sub>c,s<\/sub><\/em> are our assignment variables, <em>ms<sub>c,s<\/sub><\/em> is the \u2018match score\u2019, <em>Q<sub>s<\/sub><\/em> is the inventory, and <em>N<\/em> is our bound on the number of items to show a client. Indices <em>c<\/em> and <em>s<\/em> refer to clients and items respectively. Our objective is to maximize the expected sales. Generally, the solution time to solve an arbitrary IP using a standard solver like Gurobi\/CPLEX scales poorly with the size of the problem. Solving the above inventory targeting problem using traditional solvers with the amount of clients and merchandise that Stitch Fix deals with quickly becomes computationally intractable.<\/p>\n\n<p>Network flow algorithms to the rescue!<\/p>\n\n<p>Special cases of the assignment problem can be re-framed and solved using polynomial time network flow algorithms such as the well known push-relabel algorithm [1]. To do this, we re-frame our problem as a directed graph <em>G(V,A)<\/em> with vertices <em>V<\/em> and arcs <em>A<\/em> and search for a \u2018flow\u2019 (an assignment of real values to the arcs) from the clients to the products that represent our assignment decisions.<\/p>\n\n<p>I spent the bulk of my internship researching and implementing a generalized network flow algorithm called the Wallacher-Style GAP Canceling algorithm [2] that can handle the unique inventory constraint above that bounds expected sales by the product inventory. This constraint disqualifies some of the more popular maximum-flow algorithms because we are not able to work with integers in our graph representation. In addition, domain knowledge allowed me to develop problem-specific heuristics and warm start procedures that further improved the performance of the algorithm for our application. In the future, the fast solver for the Freestyle assignment problem that I developed will enable us to re-solve the problem as the inventory assortment changes to provide a better client experience and make sure every client sees the best in stock merchandise available.<\/p>\n\n<p>References:\n[1] A V Goldberg and R E Tarjan. 1986. A new approach to the maximum flow problem. In Proceedings of the eighteenth annual ACM symposium on Theory of computing (STOC \u201886). Association for Computing Machinery, New York, NY, USA, 136\u2013146. https:\/\/doi.org\/10.1145\/12130.12144\n[2] Restrepo, M., Williamson, D.P. A simple GAP-canceling algorithm for the generalized maximum flow problem. Math. Program. 118, 47\u201374 (2009). https:\/\/doi.org\/10.1007\/s10107-007-0183-8<\/p>\n\n<hr \/>\n<h3 id=\"style-level-true-demand-forecasting\">Style-level True Demand Forecasting<\/h3>\n<p style=\"font-size:1rem\"><i>Pau Korpajarasoontorn, MS Analytics student at Georgia Institute of Technology<\/i><\/p>\n\n<p>Stitch Fix relies heavily on algorithms to recommend styles that best match client\u2019s preferences. However, the algorithms can\u2019t perform at their best without  proper inventory depth of each style. I worked with the Merch Algorithms team to build a style-level true demand forecasting model to assist their inventory purchase decisions.<\/p>\n\n<p>Sales can only inform the censored demand because it is capped by inventory, but (true) demand isn\u2019t. If we have experienced stockout and only rely on historical sales data for future inventory purchase decisions, we will be underestimating the true demand and suffer from lost sales. This is why we attempt to forecast demand instead of sales.<\/p>\n\n<p>We divided this problem into two parts - demand imputation and demand forecasting. There is no ground truth to the demand imputation problem since we do not know the actual demand. We thus cannot apply the traditional supervised learning approach. We used a regression model instead to infer the true demand. Our regression model first estimates the impact of availability on censored demand controlling for seasonality. We then use the model to estimate the increase in demand had we maintained the target availability (the counterfactual). As shown in figure 1, the model works as desired - it imputes more when the style is within its selling season and the inventory availability is low.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <img alt=\"xxx\" src=\"\/assets\/posts\/2022-12-12-internship\/korpa_plot.png\" width=\"100%\" \/>\n\n  <figcaption style=\"text-align:center\"><i>\n Figure 1. The top and middle plots illustrate availability and seasonality of a style. The bottom plot illustrate the actual and imputed demand of the style. Blue area indicates periods of low availability in high-selling season, and red area indicates a period of low availability in low-selling season. The imputed demand is much higher than actual demand in blue areas while the model doesn\u2019t increase demand much in red area.<\/i><\/figcaption>\n<\/figure>\n\n<p>For demand forecasting, we adopted N-BEATS [1], a deep neural network architecture for interpretable time series forecasting. We use the imputed demand of all styles from the previous part as inputs to train the model. The model is trained to take 52-week lookback data and forecast 26-week demand. It beats the baseline forecasts by 18% and 8% on Mean Absolute Squared Error and Symmetric Mean Absolute Percentage Error, respectively. \nThis project is an early attempt to explore true demand forecasting with state-of-the-art methods which also provides a framework for future improvement.<\/p>\n\n<p>References:\n[1] Boris N. Oreshkin et al. \u201cN-BEATS: Neural basis expansion analysis for in-terpretable time series forecasting\u201d. In: International Conference on Learning Representations. 2020. \nurl: https:\/\/openreview.net\/forum?id=r1ecqn4YwB<\/p>\n\n<hr \/>\n<h3 id=\"predict-the-look--sfix--trend-level-analysis\">Predict the Look @ SFIX \u2013 Trend-Level Analysis<\/h3>\n<p style=\"font-size:1rem\"><i>Anna Dai, Master Student in Interdisciplinary Data Science at Duke University <\/i><\/p>\n\n<p>Curating an inventory as great as our client base at scale is at the core of Stitch Fix\u2019 success. Our Merchandising team work tirelessly to purchase and design the right pieces for our clients each season by referencing sophisticated algorithms built upon historical data as well as external research on fashion trends. As an intern on the Merchandising Algorithms team, I spent my time at Stitch Fix investigating how we can instead incorporate external fashion trends into our algorithms to better inform inventory purchasing decisions ahead of time and how viable that might be to implement.<\/p>\n\n<p>For the scope of my internship, I had to first narrow down my goals. After speaking with various internal teams and external vendors to understand what trends data are currently being leveraged manually, I identified a number of viable data sources in both text-form and image-form and ultimately decided to pursue a natural language processing (NLP) approach due to the quality of data I could access. From here, I aimed to build a steel-thread attempt at quantifying these trend terms as measurable metrics of Stitch Fix inventory in order to facilitate further analysis. In other words, I wanted to answer: \u201cTo what extent is <trend term=\"\"> trending at Stitch Fix?\u201d.<\/trend><\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <img alt=\"xxx\" src=\"\/assets\/posts\/2022-12-12-internship\/dai_diagram.png\" width=\"100%\" \/>\n<\/figure>\n\n<p>To begin, I pre-processed my data to extract a dataset of 758 unique terms related to women\u2019s fashion in 2017 through 2022 as well as their trend predictions (i.e. \u201cemerging\u201d, \u201cpeaking\u201d, \u201csafe bets\u201d, \u201cdeclining\u201d) from Trendalytics reports*. Next, I attempted different approaches to map these trend terms to Stitch Fix inventory. This mapping was particularly challenging because trend terms are diverse and ever-evolving, so we will not be able to construct a comprehensive list of all terms we might be interested in understanding. To address this, I had initially tried to pool inventory by existing attributes (i.e. color, material, silhouette) that most frequently occur in trend terms, but quickly realized that such static pooling would not be representative of most terms (e.g. white jeans might be trending but not white dresses, so we would run into too much noise if we pooled by color). Instead, I built dynamic pools of inventory that are associated with each trend term by tokenizing each term and projecting each token to the most-appropriate Stitch Fix attributes to filter upon through pre-trained word embeddings (i.e. Word2Vec[1], GloVe [2]). While this approach is highly effective for some terms, the limitations were also noticeable for our use case \u2013 \u201cblack\u201d was close to \u201cwhite\u201d and \u201clong-sleeve\u201d was close to \u201cshort-sleeve\u201d in these vector spaces so the projection scores were quite high for contrary terms.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <img alt=\"xxx\" src=\"\/assets\/posts\/2022-12-12-internship\/dai_diagram2.png\" width=\"100%\" \/>\n<\/figure>\n\n<p>I decided to proceed only with terms that have near-perfect projection scores as \u201cterms understood\u201d. From here, I leveraged our newly deployed search functionality for Freestyle customers to identify the most relevant inventory for each search term. Several limitations of this implementation stem from the fundamentally different use case \u2013 trend analysis is more restrictive than search \u2013 as well as the non comparable relevance scores outputted from Elasticsearch (based on TF-IDF[3]), which I temporarily mitigated by heavily modifying the search pipeline to filter on each token and checking the final outputs against our existing latent style space. With the current implementation, my system was able to understand only around 30% and confidently map 10% of inputted trend terms, but the key advantage of the system is that it will continue to evolve automatically as our search functionality evolves, reducing duplicative work. From here, we open the door to trend-level analysis and modeling. Stay tuned for future work!<\/p>\n\n<p>References:\n[1] Tomas Mikolov, Kai Chen, Greg Corrado, and Je\ufb00rey Dean. E\ufb03cient estimation of word representations in vector space, 2013. \n[2] Je\ufb00rey Pennington, Richard Socher, and Christopher D. Manning. Glove: Global vectors for word representation. In Empirical Methods in Natural Language Processing (EMNLP), pages 1532\u20131543, 2014.\n[3] KonradBeiske. Similarity in elasticsearch, Nov 2013.\nurl: https:\/\/www.elastic.co\/blog\/found-similarity-in-elasticsearch<\/p>\n\n","pubDate":"Tue, 03 Jan 2023 09:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/01\/03\/intern-post\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2023\/01\/03\/intern-post\/"},{"title":"Leveraging the Plain Old Python Function","description":"<style>\ntable.plain-old-python-functions {\n  margin: 0 auto calc(0.5rem + 15px);\n  width: 100%;\n}\ntable.plain-old-python-functions th {\n  font-weight: normal;\n  text-align: right;\n}\ntable.plain-old-python-functions th div.MathJax_Display {\n  text-align: right !important;\n}\ntable.plain-old-python-functions tr:nth-child(even) {\n  background-color: #F2EFEA;\n}\ntable.plain-old-python-functions td {\n    border-bottom: 1px solid #cdcac8;\n    padding: 0.5em;\n    text-align: left;\n}\n\nfigure figcaption {\n    text-align: center;\n}\n<\/style>\n\n<p>The role of the <em>full-stack-data-scientist<\/em> is not what it once was.<\/p>\n\n<p>With the advent of more powerful tooling, new industry standards in MLOps, and greater investment in platforms, the day-to-day of a data scientist has changed significantly at Stitch Fix. The difference, however, is subtle. The structure of their job remains the same \u2013 <em><a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2016\/03\/16\/engineers-shouldnt-write-etl\/\">engineers still do not write ETLs<\/a><\/em> and <em><a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2019\/03\/11\/FullStackDS-Generalists\/\">data scientists function as generalists<\/a><\/em>, but they now have to think on a higher level. Their job is constantly getting more and more complex\u2014the business needs are in flux and the infrastructure they use is more powerful than it ever was. The old strategy of cobbling together complex systems will only end in stressed-out data scientists with too much infrastructure on their plate.<\/p>\n\n<p>To avoid this cycle of complexity, Stitch Fix invests in a platform team to innovate new ways of supporting a data scientist\u2019s engineering needs. Rather than constructing custom model-deployment mechanisms, building microservices from the ground up, and managing highly interdependent chains of data transformations, data scientists at Stitch Fix can leverage powerful infrastructure by <strong>constructing plain old Python functions to represent their needs<\/strong>.<\/p>\n\n<p>In this blog post we\u2019re going to take a different approach than usual. Rather than digging into a specific piece of technology, we\u2019ll present our philosophy of functions for data science APIs and back it up with some motivating examples. We\u2019ll explain the power of functions as a DSL, share some successes we\u2019ve had using functional interfaces to build our MLOps stack, and connect our approach with external, open-source frameworks that the industry is beginning to adopt. Our goal is to convince you that a function-first approach will enable data practitioners to do more while doing less. The functional approach allows them to plug into the business in a scalable manner while avoiding the complexity of managing infrastructure and architectural decisions.<\/p>\n\n<h1 id=\"on-functions-and-functionality\">On Functions and Functionality<\/h1>\n\n<p>Since way before many of us were born, the software industry has been battling between <em>functional<\/em> and <em>procedural<\/em> programming paradigms. Do you offer imperative commands over the operations of your system? Or do you declare the intent and let some system in the background handle the operations for you? While we won\u2019t opine on this age-old debate, we do bring this up for a reason. At Stitch Fix, data scientists get the best of both worlds:<\/p>\n\n<ul>\n  <li>They can declare infrastructure and plug into the business by writing python functions to fit into platform-provided frameworks<\/li>\n  <li>They can specify custom model and business logic by implementing said functions<\/li>\n<\/ul>\n\n<p>At the core, we believe data scientists should <em>only<\/em> have to think about business logic, and all else (infrastructure, etc\u2026) should be given to them on a silver platter. The delineation of responsibilities here is critical in providing high-power tooling to allow data scientists to plug into the business, and Python functions happen to be the perfect way to codify it. The name, type annotations, decorators, and parameters of a function all provide plenty of information to declare the structure of the systems they need. The guts of a function allow a data scientist to iterate on and cleanly represent their business logic.<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"o\">@<\/span><span class=\"n\">do_something_fancy_with_function<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">my_function<\/span><span class=\"p\">(<\/span><span class=\"n\">param_1<\/span><span class=\"p\">:<\/span> <span class=\"n\">pd<\/span><span class=\"p\">.<\/span><span class=\"n\">Series<\/span><span class=\"p\">,<\/span> <span class=\"n\">param_2<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">pd<\/span><span class=\"p\">.<\/span><span class=\"n\">Series<\/span><span class=\"p\">:<\/span>\n    <span class=\"s\">\"\"\"Does a thing with some params\"\"\"<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">fancy_business_logic<\/span><span class=\"p\">(<\/span><span class=\"n\">param_1<\/span><span class=\"p\">,<\/span> <span class=\"n\">param_2<\/span><span class=\"p\">)<\/span> \n<\/code><\/pre><\/div><\/div>\n\n<table class=\"plain-old-python-functions\">\n  <tr>\n   <td><strong>Function Name <\/strong>\n   <\/td>\n   <td><code>my_function<\/code>\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Type Annotations<\/strong>\n   <\/td>\n   <td><code>pd.Series, int<\/code>\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Decorators<\/strong>\n   <\/td>\n   <td><code>@do_something_fancy_with_function<\/code>\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Parameters<\/strong>\n   <\/td>\n   <td><code>param_1, param_2<\/code>\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Docstring<\/strong>\n   <\/td>\n   <td><code>\"\"\"Does a thing with some params\"\"\"<\/code>\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Logic<\/strong>\n   <\/td>\n   <td><strong><code>return fancy_business_logic(param_1, param_2)<\/code><\/strong>\n   <\/td>\n  <\/tr>\n<\/table>\n\n<p>How do we actually link this metadata to give data scientists MLOps capabilities? Let\u2019s go through a few examples\u2026<\/p>\n\n<h1 id=\"functional-capabilities\">Functional Capabilities<\/h1>\n\n<h2 id=\"productionizing-models\">Productionizing Models<\/h2>\n\n<p>Years ago, releasing a model at Stitch Fix took considerable effort. To execute a model in a production context (batch\/online), data scientists had to:<\/p>\n\n<ol>\n  <li>Save the model blob to a blob store<\/li>\n  <li>Build a service or a batch job that exposed their model, with Python requirements that exactly matched training<\/li>\n  <li>Download the model into the appropriate production context, updating as needed<\/li>\n  <li>Maintain and manage the service\/batch job<\/li>\n<\/ol>\n\n<p>This regularly repeated chain of micromanaged infrastructure was not nimble enough to support the velocity at which data scientists at Stitch Fix work. So, we built new tooling that enables data scientists to publish their model to production by:<\/p>\n\n<ol>\n  <li>Saving a function using our API<\/li>\n  <li>Configuring deployment through a centralized model-management service<\/li>\n<\/ol>\n\n<p>To write a model, one need simply implement a Python function (we\u2019re not picky \u2013 a model can be <em>any<\/em> python function) and save it to the platform-provided API. This provides a host of capabilities to choose from with the push of a button: a data scientist can run their model over a large dataset on Spark, deploy in a platform-managed online service context to respond to http requests, track\/manage\/add metrics, and set up CI\/CD. To gather the requisite model information for the platform to carry out these capabilities, we take advantage of everything the data scientist\u2019s function provides us:<\/p>\n\n<table class=\"plain-old-python-functions\">\n  <tr>\n   <td><strong>Function Name <\/strong>\n   <\/td>\n   <td>Delineates this query on the model from others\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Annotations<\/strong>\n   <\/td>\n   <td>Specifies types for model inputs\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Parameters<\/strong>\n   <\/td>\n   <td>Allows us to generate openAPI docs, connect to features\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Logic<\/strong>\n   <\/td>\n   <td>Enables actual model evaluation!\n   <\/td>\n  <\/tr>\n<\/table>\n\n<p>We use a little more than this to add additional metadata\u2014see the <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/07\/14\/deployment-for-free\/\">full writeup<\/a> for more details. That said, the core principle is simple. By reading the code and looking at the function a data scientist writes, we should be able to understand its role in the business and provide the infrastructure it requires.<\/p>\n\n<h2 id=\"writing-services\">Writing Services<\/h2>\n\n<p>At Stitch Fix, our data scientists write and manage services, beyond those that can be represented by writing models (they\u2019re on call, even!).  Constructing\/managing a service generally requires a lot of architectural decisions. What framework do you use? How do you specify\/validate the shape of the input? How do you handle errors? And so on\u2026<\/p>\n\n<p>At Stitch Fix, the platform team has made it very easy to manage decisions. All a data scientist has to do is write a simple set of functions to specify their service\u2019s endpoints.  Built on top of FastAPI + Uvicorn, Stitch Fix\u2019s service toolkit gives a data scientist the power of a full-scale web application.<\/p>\n\n<p>While we have not yet blogged about this, the API is simple enough for Data Scientists to go from zero to a production service in an hour. What does it look like?<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"o\">@<\/span><span class=\"n\">get<\/span><span class=\"p\">(<\/span><span class=\"s\">'\/v0\/api\/recommendations'<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">get_recommendations<\/span><span class=\"p\">(<\/span><span class=\"n\">customer_id<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">List<\/span><span class=\"p\">[<\/span><span class=\"n\">Recommendation<\/span><span class=\"p\">]:<\/span>\n    <span class=\"s\">\"\"\"Provides recommendations for a customer\"\"\"<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">some_business_logic<\/span><span class=\"p\">(...)<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<table class=\"plain-old-python-functions\">\n  <tr>\n   <td><strong>Annotations<\/strong>\n   <\/td>\n   <td>Specifies types for generating documentation\/validating.\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Decorators<\/strong>\n   <\/td>\n   <td>Specifies method type, endpoint, tags for organization. Enables distributed tracing. Registers function for use with FastAPI route.\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Parameters<\/strong>\n   <\/td>\n   <td>Allows validating of inputs, generates API signature.\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Docstring<\/strong>\n   <\/td>\n   <td>Generates openAPI documentation.\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Guts<\/strong>\n   <\/td>\n   <td>Does the business logic.\n   <\/td>\n  <\/tr>\n<\/table>\n\n<p>Again, we don\u2019t always use every part of the function (the name, in this case, is supplanted by the endpoint path), but from reading just the snippet of code above, it should be clear (a) where this fits in the business and (b) how this manifests in the infrastructure.<\/p>\n\n<h2 id=\"transforming-data\">Transforming Data<\/h2>\n\n<p>The vast majority of code data scientists write transforms data from one shape to another. Data transformations are a natural way to iteratively present value to the business, but representing them in code can be challenging. Scientists often develop their own methods of organizing and executing these transformations, which range from monolithic scripts to custom-built sophisticated pipelining mechanisms. While these get the job done, as teams switch up, goals change, and initiatives are cast aside or rushed into production, the details of these bespoke methodologies become long-forgotten. To solve this problem and allow our data teams to scale with the complexity of the business, we built and open-sourced a framework called <a href=\"https:\/\/github.com\/stitchfix\/hamilton\">hamilton<\/a>.<\/p>\n\n<p>Initially designed for feature engineering, <em>hamilton<\/em> enables a data scientist to express a complex data pipeline as a series of functions; each function encodes the upstream dependencies, the data type, and the referenceable artifact.<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"o\">@<\/span><span class=\"n\">config<\/span><span class=\"p\">.<\/span><span class=\"n\">when<\/span><span class=\"p\">(<\/span><span class=\"n\">region<\/span><span class=\"o\">=<\/span><span class=\"s\">\"US\"<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">my_artifact<\/span><span class=\"p\">(<\/span><span class=\"n\">dep_1<\/span><span class=\"p\">:<\/span> <span class=\"n\">pd<\/span><span class=\"p\">.<\/span><span class=\"n\">Series<\/span><span class=\"p\">,<\/span> <span class=\"n\">dep_2<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">pd<\/span><span class=\"p\">.<\/span><span class=\"n\">Series<\/span><span class=\"p\">:<\/span>\n    <span class=\"s\">\"\"\"does something fancy with dep_1 and dep_2\"\"\"<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">_some_fancy_logic<\/span><span class=\"p\">(<\/span><span class=\"n\">dep_1<\/span><span class=\"p\">,<\/span> <span class=\"n\">dep_2<\/span><span class=\"p\">)<\/span> \n<\/code><\/pre><\/div><\/div>\n\n<table class=\"plain-old-python-functions\">\n  <tr>\n   <td><strong>Function Name <\/strong>\n   <\/td>\n   <td>Name of the artifact generated by the fn\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Annotations<\/strong>\n   <\/td>\n   <td>Types of the artifact\/dependencies\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Decorators<\/strong>\n   <\/td>\n   <td>Configuration, higher-level operations\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Parameters<\/strong>\n   <\/td>\n   <td>Name of the upstream dependencies\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Docstring<\/strong>\n   <\/td>\n   <td>Enables automatic generation of documentation\n   <\/td>\n  <\/tr>\n  <tr>\n   <td><strong>Guts<\/strong>\n   <\/td>\n   <td>Code to generate, transform the data\n   <\/td>\n  <\/tr>\n<\/table>\n\n<p>Representing generated data as functions enables us to flexibly execute pipelines in whatever framework we want while simultaneously allowing a data scientist to write highly expressive, intuitive pipelines. Better yet, these require little knowledge of framework or infrastructure, only the libraries data scientists love and the Python code they are accustomed to writing. All they have to do is write the function \u2013 the rest comes for free.<\/p>\n\n<p>We\u2019ve written about hamilton before (we\u2019re very proud): read prior posts <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2021\/10\/14\/functions-dags-hamilton\/\">introducing the framework<\/a>, <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/02\/22\/scaling-hamilton\/\">talking about scale<\/a>, and sharing <a href=\"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/07\/26\/hamilton-data-quality\/\">how we enable data validation<\/a>.<\/p>\n\n<h1 id=\"open-source-and-beyond\">Open Source and Beyond<\/h1>\n\n<p>One of Stitch Fix\u2019s greatest assets is our innovative set of data scientists who optimize the customer experience every step of the way. Without the proper tooling, however, they would get bogged down in details of infrastructure and architecture. They need control over the stack they run to operate independently, but cannot afford to be slowed down with its minutiae. Thus, it falls to the platform team to deliver tooling that makes data scientists efficient and productive. At Stitch Fix we iterated on many designs, and found that, as is often the case, the simplest solution was the best. To express business logic, data scientists write plain old Python functions. The associated metadata, structure, and contents of these functions yield enough information for an insightful platform team to plug the data science innovations back into the business.<\/p>\n\n<p>Python functions are comfortable to write, easy to debug, and straightforward to read and maintain. Add in a little config, and we\u2019ve got a fully-fledged, highly-expressive API!<\/p>\n\n<p>We believe this API approach has implications far past the frontiers of our own data science efforts. Aside from our own open-source tools, we\u2019ve begun to notice it creep up elsewhere:<\/p>\n\n<ul>\n  <li>Dagster\u2019s<a href=\"https:\/\/dagster.io\/blog\/software-defined-assets\"> software-defined-assets<\/a>_ _are one of many Python APIs that specify transformations on data through the orchestration framework<\/li>\n  <li><a href=\"https:\/\/docs.pytest.org\/en\/6.2.x\/fixture.html\">Pytest fixtures<\/a> actually use the same concept as hamilton to inject data into Python tests<\/li>\n  <li><a href=\"https:\/\/metaflow.org\/\">metaflow<\/a> allows definitions of functions specifying steps to modify workflow state<\/li>\n  <li>\u2026and so on<\/li>\n<\/ul>\n\n<p>These (and more) amazing frameworks confirm our priors that APIs of this flavor are the future. This API has been essential in enabling data scientists to focus on what matters most. Serving the customer better, optimizing operations, and providing lasting, high-caliber tools that empower the next generation to reach even greater heights.<\/p>\n\n","pubDate":"Wed, 14 Dec 2022 09:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/12\/14\/plain-old-python-functions\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/12\/14\/plain-old-python-functions\/"},{"title":"Client Time Series Model: a Multi-Target Recommender System based on Temporally-Masked Encoders","description":"<h1 id=\"introduction\">Introduction<\/h1>\n\n<p>The foundation of our recommendation stack is a scoring model we call p(sale), which estimates the probability that any given client will purchase any given item. This model has gone through many iterations over the years, from a mixed effects model, to a matrix factorization model, and now to a novel sequence-based model. Internally we call this the Client Time Series Model (aka CTSM) because of its focus on the time-domain of client interactions. This post details our new model, which is a significant improvement for both the quality of our recommendations and the maintainability of our systems.<\/p>\n\n<h1 id=\"motivation\">Motivation<\/h1>\n\n<p>Before setting out to develop our new model, it was clear that the evolution of our business necessitated a change to our modeling approach. First, the growing variety of recommendations we serve led to an explosion in the number of models we needed to maintain. Each time the business expanded, such as adding Mens, or serving the UK, or adding direct shopping with Freestyle, we responded by forking a new model to serve the new channel. This was necessary because a single domain-agnostic model could not serve the new channels as well as tailored models, but over time it has increased our maintenance burden and cost of iteration.<\/p>\n\n<p>In addition to the system complexity, we also knew we had an opportunity to make better use of important signals. With data and models separated by business line, region, and channel, we had a limited ability to leverage learning across these boundaries. With a unified model, we can more seamlessly use data from US clients to improve recommendations for UK clients, or data from Fixes to improve recommendations in Freestyle.<\/p>\n\n<p>Finally, our previous approaches modeled clients via tabular data. Although they are trained on purchase events that take place in the context of a particular point in time, they did not explicitly consider the time dimension in their understanding of the client\u2019s interactions. We believed that there was significant opportunity to better capture client state by making use of the time dimension in our model architecture.<\/p>\n\n<h1 id=\"client-time-series-model\">Client Time Series Model<\/h1>\n\n<h2 id=\"unified-client-and-item-embeddings\">Unified Client and Item Embeddings<\/h2>\n\n<h3 id=\"the-client-embedding\">The Client Embedding<\/h3>\n<p>The core of our model is our representation of the client. To simplify the task of integrating many different data sources with many different prediction domains, we employ the simplifying abstraction of a single unified client embedding. Rather than modeling the client separately for each prediction domain, we learn a single client hidden state, with separate mappings to the separate domains.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <center>\n    <img src=\"\/assets\/posts\/2022-11-01-client-time-series-model\/many-to-many.png\" style=\"width: 75%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">Figure 1: Many-to-many coupling explodes maintenance &amp; complexity.<\/figcaption>\n  <\/center>\n<\/figure>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <center>\n    <img src=\"\/assets\/posts\/2022-11-01-client-time-series-model\/many-to-one-to-many.png\" style=\"width: 75%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">Figure 2: Client embedding can act as a decoupling intermediary.<\/figcaption>\n  <\/center>\n<\/figure>\n\n<p>Importantly, this client embedding is not static, but rather updates with each new interaction we observe from the client. During training, predictions are made using the client embedding as of the timestamp of the predicted event. Similarly for features, every client interaction is considered a timestamped event. For example, we do not consider a client\u2019s \u201cwaist size\u201d to be a static feature. Rather, we consider the event when the client entered their waist size. After all, the client state and preferences are not static, but may evolve over time: in our example, at one moment in time the client\u2019s waist size might have been 42, but at another moment in time it might change to 41. Using the most recent value of 41 as a feature for interactions that happened at the time it was still 42 would be incorrect. Another example of an event is an interaction with an item: at one moment in time a client might like a certain style of shoes, but as style preferences evolve, the client might prefer a different style of shoes at another moment in time. Both cases demonstrate that a client state evolves over time, and CTSM captures these dynamics.<\/p>\n\n<p>A consequence is that it is time-safe by design: by considering events chronologically, we avoid the pitfall that past observations are informed by future events, which can easily be a problem when using tabular machine learning models.<\/p>\n\n<h3 id=\"the-item-embedding\">The Item Embedding<\/h3>\n<p>We use an EmbeddingBag approach to construct embeddings of our items by summing up the embeddings we learn for item features. This is a fairly standard approach, similar to the original matrix factorization approach in the original Netflix Prize paper<sup><a href=\"#ref-netflix\">1<\/a><\/sup>. While we model clients with a single client hidden state that we then transform into embeddings for each prediction context, we use the same item embedding in all contexts. Some backtesting has shown we may not benefit from similar additional transformations to have separate item embeddings for each context.<\/p>\n\n<h2 id=\"temporally-masked-encoder-with-gated-updates\">Temporally-Masked Encoder with Gated Updates<\/h2>\n<p>A key component of CTSM is the Temporally-Masked Encoder (TME) with gated updates. The TME is similar to a transformer<sup><a name=\"back-1\" href=\"#ref-vaswani\">3<\/a><\/sup>, but is faster and easier to train. Moreover, in our backtesting results TME performed better than a traditional transformer. The main difference is that TME computes weights only once for the whole sequence rather than separately for each input as a function of queries and keys. See Figure 3 for an overview of TME.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <center>\n    <img src=\"\/assets\/posts\/2022-11-01-client-time-series-model\/tme.png\" style=\"width: 100%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">Figure 3: Temporally-Masked Encoder.<\/figcaption>\n  <\/center>\n<\/figure>\n<p>In the example in Figure 3, the embedding dimension is equal to 64. The MaskedEncoder takes a batch of updates (100 in this case), along with the current client hidden state, and passes their concatenation through a 2-layer feedforward network that yields 100 processed updates along with a single vector of weights. The weights are combined with a triangular mask in order to perform a backwards looking weighted sum. Because the updates have been ordered by time, the MaskedEncoder encodes each update as a timesafe weighted average of itself and the previous updates in the same batch, all mixed with the current client hidden state.<\/p>\n\n<p>We break down training into subsequences of updates, storing the client hidden state and passing it along from one subsequence to the next. Updates are encoded with the MaskedEncoder, and then client hidden states are updated by passing the existing client hidden state through a GRU-style gate<sup><a href=\"#ref-cho\">2<\/a><\/sup> along with an encoded update. In this way, we have some of the sequentiality of an RNN (through the GRU updating of the client hidden state) and some of the benefits of the parallelization of transformers (all updates within a subsequence are processed in parallel)  See Figure 4 for an overview.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <center>\n    <img src=\"\/assets\/posts\/2022-11-01-client-time-series-model\/gated_update.png\" style=\"width: 75%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">Figure 4: Temporally Masked Encoder with Gated Updates.<\/figcaption>\n  <\/center>\n<\/figure>\n\n<h2 id=\"instant-reflection-of-updates-to-rankings\">Instant reflection of updates to rankings<\/h2>\n\n<p>A key aspect to improve the client experience is to reflect any client\u2019s interaction with the platforms instantly in the recommended items. For example, if a client updates their profile, the recommendations on Freestyle should immediately reflect this. If a client plays Style Shuffle and subsequently orders a Fix, we want the items that are surfaced to the stylist to immediately reflect the client\u2019s likes and dislikes. In short, any update on the client profile or client interactions should be instantly reflected in all platforms. CTSM is able to efficiently deal with updates across platforms: At inference time, the only features that have to be passed to the model are all client events that have happened since training, since everything else is reflected in the client embeddings already. Since CTSM doesn\u2019t require complex feature engineering or similar, the raw (or almost raw) features can instantly be directed to CTSM as client event updates such that any recommendations reflect those recent events.<\/p>\n\n<h1 id=\"modeling-events\">Modeling events<\/h1>\n<p>There are two main flavors of events: Updates and Targets.<\/p>\n\n<h2 id=\"updates\">Updates<\/h2>\n<p>Updates are observations of some piece of information that changes our knowledge about the client state. For example, a Fix checkout or a profile change is considered an update. Updates have four components: source, timestamp, client identifier, and payload. The source identifies what type of update we are dealing with. The timestamp identifies when the event took place. The client identifier points to the client to which the update refers. The payload contains any features or information and may differ per source. However, all updates from the same context have the same payload structure. For example, the payload for a Fix checkout might contain an item embedding and an outcome, signifying whether the client purchased the item or not. Each update is then transformed into a fixed dimensional embedding, which is used as an input to the TME. See Figure 5 for an illustration of this process.<\/p>\n\n<figure align=\"center\" style=\"margin-bottom: 1rem;\">\n  <center>\n    <img src=\"\/assets\/posts\/2022-11-01-client-time-series-model\/updates.png\" style=\"width: 50%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">Figure 5: Illustration of processing Updates.<\/figcaption>\n  <\/center>\n<\/figure>\n\n<h2 id=\"targets\">Targets<\/h2>\n<p>Targets are outcomes of interest to estimate as a function of the client state. An example of a target is the probability that a client purchases an item conditional to the item being sent to the client in a Fix. Each target has an associated loss function, such as binary cross entropy. Targets may correspond to updates, but this is not required. For example, a Fix purchase may be included as an Update as well as a Target. Targets contain the same components as updates, namely source, timestamp, client identifier, and payload, but additionally requires an associated loss function that measures predictions against outcomes from the payload. In our fix checkout example from the updates, the loss function is measured against the \u2018outcome\u2019 inside the payload.<\/p>\n\n<p>To make a target prediction, the most recent client embedding prior to the target timestamp is fetched, as well as the item embedding. The client vector is then transformed to the item embedding space using a 2-layer feed-forward neural network. The dot product of the two gives us the predicted logits, which can be transformed into the predicted probability by applying the expit function. See Figure 6 for an illustration of this process.<\/p>\n\n<figure style=\"margin-bottom: 1rem;\">\n  <center>\n    <img src=\"\/assets\/posts\/2022-11-01-client-time-series-model\/targets.png\" style=\"width: 50%\" \/>\n    <figcaption style=\"margin-top: 0.5rem; text-align: center;\">Figure 6: Illustration of target prediction.<\/figcaption>\n  <\/center>\n<\/figure>\n\n<h1 id=\"concluding-remarks\">Concluding Remarks<\/h1>\n\n<p>The productionized version of CTSM has been a great success for Stitch Fix. Before rolling out the model to all our business lines, regions, and experiences, we performed A\/B tests of CTSM against the predecessor models across our Womens, Mens, and Kids business lines, across our US and the UK regions, and across our Fix and Freestyle channels. We found benefits in four main categories:<\/p>\n<ul>\n  <li>Key Performance Indices. We saw an improvement on virtually all our KPIs, such as revenue, retention, and client satisfaction.<\/li>\n  <li>Computing resources. We saw a tremendous reduction in resource consumption. First of all, we now only train one machine learning model, whereas before we trained several machine learning models, by region, business line, and shopping experience. Second, the inference endpoint consumes less resources than the combined resources needed for all predecessor models.<\/li>\n  <li>Lower maintenance. CTSM requires less maintenance than our predecessor models, because now we only have to maintain one repository, training pipeline and endpoint, while previously we had to maintain several. Also, due to the nature of CTSM we do not have to maintain complex preprocessing jobs or engineered features. We only have to input the raw features with minimal preprocessing.<\/li>\n  <li>Accelerated development. The benefits above aid us exponentially: the reduced maintenance frees up time on the team to focus on developing and improving our model and endpoint, and the unified framework has greatly accelerated our development velocity. For example, we recently developed an improved subsampling technique for the Freestyle target logic. Because CTSM handles each target as a modular component, we could do this easily and quickly in one place without touching other event sources like Fix targets or survey updates.<\/li>\n<\/ul>\n\n<p>To conclude, we are now better than ever connecting our clients with the items they love, using a more stable and computationally efficient system, and we believe that we can continue to deliver  improvements in our recommendations at an accelerated pace.<\/p>\n\n<h1 id=\"references\">References<\/h1>\n\n<p><a name=\"ref-netflix\"><\/a> [1] Yehuda Koren, Robert Bell, and Chris Volinsky. 2009. Matrix factorization techniques for recommender systems. <em>Computer<\/em> 42, no. 8 (2009): 30-37.<\/p>\n\n<p><a name=\"ref-cho\"><\/a> [2] Kyunghyun Cho, Bart van Merri\u00ebnboer, Dzmitry Bahdanau, and Yoshua Bengio. 2014. On the Properties of Neural Machine Translation: Encoder\u2013Decoder Approaches. In <em>Proceedings of SSST-8, Eighth Workshop on Syntax, Semantics and Structure in Statistical Translation<\/em>. 103\u2013111.<\/p>\n\n<p><a name=\"ref-vaswani\"><\/a> [3] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, \u0141ukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. <em>Advances in neural information processing systems<\/em> 30 (2017).<\/p>\n","pubDate":"Fri, 14 Oct 2022 06:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/10\/14\/client-time-series-model\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/10\/14\/client-time-series-model\/"},{"title":"Algo Hour - Large Scale Data & ML Monitoring with whylogs | Alessya Visnjic","description":"<h3 id=\"title\">Title:<\/h3>\n\n<p>Large Scale Data &amp; ML Monitoring with whylogs<\/p>\n\n<h3 id=\"talk-abstract\">Talk Abstract:<\/h3>\n\n<p><img src=\"https:\/\/external-preview.redd.it\/5PGoA8K2MVCIC_h7k-H0OArTtADCLNhye8fFBcfk-lM.jpg?auto=webp&amp;s=3764d7449d4475306f15278752a033cdd72d8cf7\" alt=\"whylogs\" \/>\nIn the era of microservices, decentralized ML architectures and complex data pipelines, data quality has become a bigger challenge than ever. When data is involved in complex business processes and decisions, bad data can, and will, affect the bottom line. As a result, ensuring data quality across the entire ML pipeline is both costly, and cumbersome while data monitoring is often fragmented and performed ad hoc. An open source library called <a href=\"https:\/\/github.com\/whylabs\/whylogs\">whylogs<\/a> is built to address these challenges. It is a lightweight data profiling library that enables end-to-end data monitoring across the entire software stack. The library implements a language and platform agnostic approach to data quality and data monitoring. It\u2019s been deployed at massive-scale data environments, on structured and unstructured data modalities, and across a range of points in the ML lifecycle. In this talk, we will provide an overview of the whylogs architecture, including its lightweight statistical data collection approach and we will show how users can apply this library to existing data and ML pipelines.<\/p>\n\n<h3 id=\"date-and-time\">Date and Time:<\/h3>\n\n<p>The talk will be held on Tuesday, October 11th at 1:00PM PDT.<\/p>\n\n<h3 id=\"recording-info\">Recording Info:<\/h3>\n<p>This talk was recorded live and is viewable below:<\/p>\n<iframe width=\"560\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/UK2b1pG1xbo\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen=\"\"><\/iframe>\n\n<h3 id=\"speaker-info\">Speaker Info:<\/h3>\n\n<p>Alessya Visnjic is the CEO of WhyLabs, the AI Observability company building tools that power robust and responsible AI deployment. Prior to WhyLabs, Alessya was a CTO-in-residence at the Allen Institute for AI, where she evaluated commercial potential for the latest AI research. Earlier, Alessya spent 9 years at Amazon leading ML initiatives, including forecasting and data science platforms. Alessya is also the founder of Rsqrd AI, a global community of 1,000+ AI practitioners who are committed to making enterprise AI technology responsible.<\/p>\n","pubDate":"Thu, 29 Sep 2022 09:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/09\/29\/alessya-algo-hour-announcement\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/09\/29\/alessya-algo-hour-announcement\/"},{"title":"Experts in-the-Loop at Stitch Fix","description":"<p>Imagine your job is to personalize search results on an e-commerce site for returning customers, classify the presence or absence of pedestrians in street photos, or develop an app that translates languages. In all of these cases, a basic ingredient is a dataset of annotations provided by a human. For any company seeking to personalize experience for its customers, combining <a href=\"https:\/\/en.wikipedia.org\/wiki\/Human-based_computation\">human<\/a> <a href=\"https:\/\/www.technologyreview.com\/2015\/06\/04\/248690\/the-emerging-science-of-human-computation\/\">computation<\/a> with algorithmic computation is essential. This is also true for Stitch Fix.<\/p>\n\n<p>At Stitch Fix, we recently launched Stitch Fix <a href=\"https:\/\/newsroom.stitchfix.com\/blog\/launch-of-stitch-fix-freestyle\/\">Freestyle<\/a>, our direct-shopping experience, where our algorithmic recommendations are now directly shared with clients in their own personal shopping feed \u2013 a different approach from our original Fix experience, where a team of expert stylists determined what should go in the client\u2019s Fix. Central to the Freestyle experience for clients is showing individual items as part of complete outfits, where both items and outfits are personalized based on our clients unique size, fit, style, and price preferences.<\/p>\n\n<h4 id=\"but-what-makes-a-good-outfit-and-how-do-we-balance-personalization-to-a-customer-with-a-given-level-of-outfit-quality-or-a-particular-stylistic-slant\">But, what makes a good outfit? And, how do we balance personalization to a customer with a given level of outfit quality or a particular stylistic slant?<\/h4>\n\n<p>In order to bootstrap a new product like this, to offer personalized outfit recommendations at scale to our around 4m clients, we need some high-quality training data. In particular, we need data specific to what it means to have a good client experience - or what makes a good outfit for a given client at Stitch Fix. Datasets like this aren\u2019t exactly floating around: assembling them requires an intentional, large-scale effort. The best way to get high-quality data sets is to work with our in-house experts: our stylists.<\/p>\n\n<p>In this post, you\u2019ll learn more about the purpose and impact of stylist-in-the-loop projects, and the powerful impact that our stylists have in building the future of personalized shopping.<\/p>\n\n<h4 id=\"bringing-in-our-experts-in-the-loop\">Bringing in our \u201cexperts in-the-loop\u201d<\/h4>\n<p>Working with our expert stylists helps us improve our clients\u2019 experience in a number of ways. In building this new Freestyle experience from scratch, we had to make decisions about how we would measure the value added for our clients. This was especially important, because if we\u2019re showing recommendations to clients without stylists\u2019 judgment beforehand (like in the Fix experience), how would we know if our algorithmic recommendations were good? We know we could measure indirect customer metrics like engagement and revenue, but we also recognized we could measure this by tapping into our expert stylists, and asking them to give their opinion.<\/p>\n\n<p>To give an example of how we bring our experts in-the-loop with our algorithms, I\u2019ll illustrate how we do this in the context of building outfits for your \u201cTrending for You\u201d and \u201c<a href=\"https:\/\/newsroom.stitchfix.com\/blog\/introducing-the-latest-ways-we-are-making-it-even-easier-for-you-to-discover-the-things-you-love-with-shop\/\">Complete Your Looks<\/a>\u201d shops in Freestyle. The first step is <strong>Outfit QA<\/strong>.<\/p>\n\n<p>Each day, a random sample of the day\u2019s algorithmically-generated outfits shared with clients is collected and stored. Then, our styling experts evaluate - against a developed set of criteria and using a specific labeling tool - what makes a good outfit. The evaluation criteria was developed in conjunction with members of our styling field, to ensure that we were maximizing the expertise of our Styling Team Leads and their stylistic judgment based on their own expertise and deep understanding of our clients.<\/p>\n\n<h4 id=\"measuring-the-impact\">Measuring the impact<\/h4>\n<p>As we reviewed the impact of our Outfit QA project, we saw three key areas of opportunity:<\/p>\n\n<ol>\n  <li>It gave us a better understanding of loss patterns, for example:\n    <div style=\"text-align:center\">\n   <img src=\"\/assets\/posts\/2022-09-02-stylists-in-the-loop\/loss-patterns.png\" width=\"80%\" \/>\n <\/div>\n  <\/li>\n  <li>\n    <p>It helped us understand and prioritize model improvements.<\/p>\n  <\/li>\n  <li>Importantly, it gave us training data to build a predictive model to estimate the likelihood of a given outfit having a QA problem. This is a tool we are able to use to help evaluate outfits before showing them to clients.<\/li>\n<\/ol>\n\n<h4 id=\"outfit-creation-at-scale\">Outfit Creation at Scale<\/h4>\n<p>Now that we know what problem areas to improve, where should the training data come from? Our inventory is changing constantly \u2013 seasons change, tastes change \u2013 so our training data needs to stay fresh, relevant, and on-brand. We again turn to our styling experts, working in conjunction with an algorithmic process, to keep us informed. This is the second step for our outfit-building project: <strong>Stylist-Generated Outfits<\/strong>.<\/p>\n\n<p>Our initial goal with stylist-generated outfits was to build a process for a continually refreshing dataset to feed into the outfits we show in \u201cShop Your Looks\u201d and \u201cTrending for You\u201d. As trends in fashion change often, and our inventory changes to reflect them, we needed to build an outfit model that would easily adapt and not risk becoming stale.<\/p>\n\n<p>We built a tool that allows our stylists to sample available inventory and create outfits. This new tool enabled us to scale our effort beyond what was originally envisioned, and bring new value to our clients by sharing outfit inspiration, or \u201cWays to Wear It\u201d, for individual items in their curated Freestyle Shops. Because of the scale at which stylists were able to create outfits using this tool, we were also able to ask an unconventional question: what if we recommend stylist-generated outfits alongside our algorithmically-generated ones?<\/p>\n\n<p>In an early test, the stylist outfits were very well-received by clients. We also tested our original hypothesis of using the stylist outfits as training data to improve the model directly. This resulted in a lift to observed Freestyle customer metrics, including revenue, as well as a 14% increase in our internal quality measure, as enabled by the Outfit QA project above.<\/p>\n\n<h4 id=\"whats-next\">What\u2019s next?<\/h4>\n<p>The experimentation with Outfit QA and Stylist-Generated Outfits project created new opportunities for showcasing stylist expertise in our Freestyle experience. By bringing our style experts together with our algorithms, we were able to improve the client experience.<\/p>\n\n<p>Our stylist expertise is a unique differentiator in terms of the algorithmic products we are able to bootstrap in this way. It takes time to develop an organic and nuanced understanding of a domain, and our stylists have built-in, relevant knowledge they bring to these systems: they know style <em>and<\/em> they know their clients.<\/p>\n\n<p>We\u2019ve only started to scratch the surface with these kinds of human-in-the-loop machine learning experiments. More updates and initiatives to come!<\/p>\n","pubDate":"Fri, 02 Sep 2022 09:00:00 +0000","link":"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/09\/02\/stylists-in-the-loop\/","guid":"https:\/\/multithreaded.stitchfix.com\/blog\/2022\/09\/02\/stylists-in-the-loop\/"}]}}