<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Juan-Luis García-Mendoza on Medium]]></title>
        <description><![CDATA[Stories by Juan-Luis García-Mendoza on Medium]]></description>
        <link>https://medium.com/@juanluis1702?source=rss-9ed3edbf79ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6-GSO1BzLzaphetHv6WowA.jpeg</url>
            <title>Stories by Juan-Luis García-Mendoza on Medium</title>
            <link>https://medium.com/@juanluis1702?source=rss-9ed3edbf79ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:06:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juanluis1702/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Desplegando Jaeger, Prometheus y Grafana con Docker Compose]]></title>
            <link>https://medium.com/@juanluis1702/desplegando-jaeger-prometheus-y-grafana-con-docker-compose-0098a22b7c37?source=rss-9ed3edbf79ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/0098a22b7c37</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[jaegertracing]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[grafana-dashboard]]></category>
            <dc:creator><![CDATA[Juan-Luis García-Mendoza]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 16:50:11 GMT</pubDate>
            <atom:updated>2026-01-18T16:50:11.418Z</atom:updated>
            <content:encoded><![CDATA[<p>En este artículo, se explica cómo desplegar una solución de monitorización y trazabilidad distribuida utilizando <a href="https://www.jaegertracing.io/"><strong>Jaeger</strong></a>, <a href="https://prometheus.io/"><strong>Prometheus</strong></a> y <a href="https://grafana.com/"><strong>Grafana</strong></a>. Se utilizará <strong>Docker Compose</strong> para gestionar la infraestructura de forma simple y reproducible.</p><p><em>English version available </em><a href="https://medium.com/@juanluis1702/deploying-jaeger-prometheus-and-grafana-with-docker-compose-87d3bd499bbe"><em>here</em></a></p><h4><strong>Introducción</strong></h4><p>El stack que desplegaremos consta de los siguientes componentes:</p><figure><img alt="Arquitectura de Monitorización con Jaeger, Prometheus y Grafana" src="https://cdn-images-1.medium.com/max/840/0*dbLuonQzVMvOPk0m.png" /><figcaption>Arquitectura de Monitorización con Jaeger, Prometheus y Grafana</figcaption></figure><ul><li><strong>Jaeger </strong>es un sistema de trazabilidad distribuida de código abierto utilizado para monitorizar y solucionar problemas en arquitecturas complejas de microservicios. Rastrea las solicitudes a medida que fluyen a través de múltiples servicios, visualizando dependencias e identificando cuellos de botella de rendimiento o errores. Esto permite a los desarrolladores optimizar el rendimiento, detectar problemas rápidamente y obtener información detallada sobre sus sistemas distribuidos.</li><li><strong>Prometheus </strong>es una herramienta de monitorización y alertas de código abierto. Recopila métricas de series temporales de aplicaciones y sistemas, almacenándolas en una base de datos de series temporales. Gracias a su potente lenguaje de consultas, Prometheus permite un análisis exhaustivo de estas métricas. Los equipos utilizan <strong>Prometheus </strong>para monitorear la salud y el rendimiento de sus aplicaciones, configurar alertas basadas en umbrales y visualizar datos mediante dashboards. Es una herramienta esencial para la observabilidad en entornos de microservicios y sistemas distribuidos.</li><li><strong>Grafana </strong>es una plataforma de visualización de código abierto que permite crear dashboards interactivos y personalizables para monitorear y analizar datos de diversas fuentes. Se integra perfectamente con bases de datos de series temporales como <strong>Prometheus</strong>, así como con otros sistemas de monitoreo. <strong>Grafana </strong>facilita la creación de visualizaciones claras y concisas de métricas, logs y trazas, ayudando a los equipos a comprender mejor el rendimiento de sus aplicaciones y sistemas.</li></ul><h4><strong>Repositorio y Código Fuente</strong></h4><p>Puedes encontrar el código fuente completo y los archivos de configuración en el <a href="https://github.com/juanluis17/medium-blog/tree/main/observability/simple">repositorio de GitHub</a>. ¡Siéntete libre de clonar, contribuir o abrir issues si tienes alguna pregunta!</p><h4><strong>Docker Compose Explicado</strong></h4><ol><li><strong>Jaeger</strong></li></ol><pre>jaeger:<br>  networks:<br>    backend:<br>      aliases: [ spm_metrics_source ]<br>  image: jaegertracing/jaeger:${JAEGER_VERSION:-latest}<br>  restart: always<br>  environment:<br>    - OTEL_ENABLED=true<br>  volumes:<br>    - &quot;./jaeger-ui.json:/etc/jaeger/jaeger-ui.json&quot;<br>    - &quot;./config.yml:/etc/jaeger/config.yml&quot;<br>  command: [&quot;--config&quot;, &quot;/etc/jaeger/config.yml&quot;]<br>  ports:<br>    - &quot;0.0.0.0:16686:16686&quot;<br>    - &quot;0.0.0.0:8888:8888&quot;<br>    - &quot;0.0.0.0:8889:8889&quot;<br>    - &quot;0.0.0.0:4317:4317&quot; # OTLP gRPC<br>    - &quot;0.0.0.0:4318:4318&quot; # OTLP HTTP</pre><p>Para configurar Jaeger, es esencial establecer <em>OTEL_ENABLED=true</em> para habilitar la recepción de trazas de aplicaciones instrumentadas con OpenTelemetry. Los puertos 4317 (gRPC) y 4318 (HTTP) deben exponerse para recibir datos de trazas, mientras que el puerto 16686 proporciona acceso a la interfaz web de Jaeger para visualizar las trazas recopiladas.</p><p><strong>2. Prometheus</strong></p><pre>prometheus:<br>  networks:<br>    - backend<br>  image: prom/prometheus:v3.1.0<br>  restart: always<br>  volumes:<br>    - &quot;./prometheus.yml:/etc/prometheus/prometheus.yml&quot;<br>  ports:<br>    - &quot;9090:9090&quot;</pre><p>Definir la configuración a través de un <strong>volumen </strong>permite la personalización de <strong>Prometheus </strong>sin reconstruir la imagen. Un simple reinicio de Docker carga la configuración actualizada, incluidas las configuraciones de scraping y reglas de alertas. Exponer el puerto <strong>9090 </strong>proporciona acceso a la interfaz web de <strong>Prometheus </strong>en <em>http://&lt;host_ip&gt;:9090</em>, permitiendo a los usuarios consultar métricas, ver gráficos y gestionar <strong>Prometheus</strong>.</p><p><strong>3. Grafana</strong></p><pre>grafana:<br>  image: grafana/grafana:latest<br>  restart: always<br>  networks:<br>    - backend<br>  ports:<br>    - &quot;3000:3000&quot;<br>  environment:<br>    - GF_SECURITY_ADMIN_PASSWORD=admin<br>  depends_on:<br>    - prometheus</pre><p>Exponer el puerto <strong>3000 </strong>proporciona acceso a la interfaz web de Grafana en <em>http://&lt;host_ip&gt;:3000</em>. La variable de entorno <strong>GF_SECURITY_ADMIN_PASSWORD</strong> establece la contraseña inicial del administrador. En entornos de producción, esto debe reemplazarse con una contraseña fuerte y segura.</p><h4><strong>Archivos de Configuración</strong></h4><p><strong>1. prometheus.yml</strong></p><pre>global:<br>  scrape_interval: 60s<br>  evaluation_interval: 60s<br><br>scrape_configs:<br>  - job_name: &#39;spm-metrics&#39;<br>    metrics_path: &#39;/metrics&#39;<br>    static_configs:<br>      - targets: [&#39;spm_metrics_source:8889&#39;]</pre><p>La sección <em>global</em> en Prometheus establece opciones de configuración, con <em>scrape_interval: 60s</em> y <em>evaluation_interval: 60s</em> definiendo con qué frecuencia <strong>Prometheus </strong>recopila métricas y evalúa reglas de alertas. La sección <em>scrape_configs</em> especifica de dónde <strong>Prometheus </strong>recupera métricas y el <em>job_name</em> <strong>spm-metrics</strong> identifica este trabajo. Las métricas se recopilan de <em>/metrics</em>, lo que significa que <strong>Prometheus </strong>consultará <em>http://&lt;target_address&gt;/metrics</em>. El campo <em>targets</em> (<em>spm_metrics_source:8889</em>) apunta al servicio que proporciona métricas, en este caso Jaeger por el alias de Docker Compose.</p><p><strong>2. config.yml</strong></p><pre>service:<br>  extensions: [jaeger_storage, jaeger_query]<br>  pipelines:<br>    traces:<br>      receivers: [otlp]<br>      processors: [batch]<br>      exporters: [jaeger_storage_exporter, spanmetrics]<br>    metrics/spanmetrics:<br>      receivers: [spanmetrics]<br>      exporters: [prometheus]<br><br>telemetry:<br>  resource:<br>    service.name: jaeger<br>  metrics:<br>    level: detailed<br>  readers:<br>    - pull:<br>        exporter:<br>          prometheus:<br>            host: 0.0.0.0<br>            port: 8888<br>  logs:<br>    level: DEBUG<br><br>extensions:<br>  jaeger_query:<br>    storage:<br>      traces: some_storage<br>      metrics: some_metrics_storage<br>  jaeger_storage:<br>    backends:<br>      some_storage:<br>        memory:<br>          max_traces: 100000<br>    metric_backends:<br>      some_metrics_storage:<br>        prometheus:<br>          endpoint: http://prometheus:9090<br>          normalize_calls: true<br>          normalize_duration: true<br><br>connectors:<br>  spanmetrics:<br><br>receivers:<br>  otlp:<br>    protocols:<br>      grpc:<br>        endpoint: &quot;0.0.0.0:4317&quot;<br>      http:<br>        endpoint: &quot;0.0.0.0:4318&quot;<br><br>processors:<br>  batch:<br><br>exporters:<br>  jaeger_storage_exporter:<br>    trace_storage: some_storage<br>  prometheus:<br>    endpoint: &quot;0.0.0.0:8889&quot;</pre><p>Esta configuración de OpenTelemetry Collector habilita la recepción, procesamiento y exportación de trazas y métricas utilizando <strong>Jaeger </strong>y <strong>Prometheus</strong>.</p><p>Las trazas se reciben de aplicaciones instrumentadas con OpenTelemetry a través del protocolo OTLP, escuchando en los puertos 4317 (gRPC) y 4318 (HTTP). Estas trazas se procesan en batches para mayor eficiencia y luego se exportan a Jaeger usando <em>jaeger_storage_exporter</em>, mientras que las métricas derivadas de las trazas se envían a <strong>Prometheus</strong> utilizando el conector <em>spanmetrics</em>.</p><p>Para la gestión del almacenamiento, la extensión <em>jaeger_storage</em> configura un backend en memoria capaz de almacenar hasta 100,000 trazas, mientras que <em>jaeger_query</em> permite consultar las trazas y métricas almacenadas.</p><p>Para la recepción de métricas, el conector <em>spanmetrics</em> convierte trazas en métricas para que <strong>Prometheus </strong>las recopile, con las propias métricas del collector expuestas en el puerto 8888. El procesador <em>batch</em> agrega y procesa los datos antes de exportarlos, optimizando así el rendimiento del sistema.</p><p>La configuración de telemetría define un nivel “detallado” para una mejor observabilidad, mientras que los logs a nivel DEBUG facilitan la solución de problemas. En resumen, esta configuración proporciona una solución robusta para capturar trazas, almacenarlas en <strong>Jaeger</strong>, convertirlas en métricas y monitorizarlas en <strong>Prometheus</strong>, garantizando una observabilidad completa en entornos distribuidos.</p><h4><strong>Despliegue con Docker Compose</strong></h4><p>Para iniciar los contenedores, ejecuta:</p><pre>sudo docker-compose up -d</pre><h4><strong>Verificación de Servicios</strong></h4><ul><li><strong>Interfaz de Jaeger</strong>: <a href="http://localhost:16686/">http://localhost:16686</a></li><li><strong>Prometheus</strong>: <a href="http://localhost:9090/">http://localhost:9090</a></li><li><strong>Grafana</strong>: <a href="http://localhost:3000/">http://localhost:3000</a> (Usuario: <em>admin</em>, Contraseña: <em>admin</em>)</li></ul><h4><strong>Creación de Dashboards en Grafana</strong></h4><p>Una vez que el stack esté en ejecución, puedes crear dashboards personalizados en <strong>Grafana </strong>que integren datos de <strong>Prometheus </strong>y <strong>Jaeger</strong>. Simplemente añade <strong>Prometheus </strong>como fuente de datos para visualizar métricas y <strong>Jaeger </strong>para analizar trazas, habilitando una configuración completa de monitoreo y observabilidad.</p><h4><strong>Conclusión</strong></h4><p>En este artículo, desplegamos con éxito un stack completo de observabilidad utilizando <strong>Jaeger</strong>, <strong>Prometheus </strong>y <strong>Grafana </strong>con Docker Compose. Esta configuración proporciona una solución potente y escalable para trazabilidad distribuida, monitorización y visualización de datos.</p><p>Este despliegue permite a los equipos obtener información detallada sobre sus aplicaciones, detectar problemas de forma temprana y optimizar el rendimiento con un esfuerzo mínimo de configuración. Ya sea gestionando microservicios, solucionando problemas de latencia o garantizando la fiabilidad del sistema, este stack de observabilidad es una base sólida para mejorar la visibilidad de tu infraestructura.</p><h4><strong>Referencias</strong></h4><p>[1] <a href="https://www.jaegertracing.io/docs/2.4/deployment/">Jaeger Deployment.</a></p><p>[2] <a href="https://github.com/jaegertracing/jaeger/tree/v2.4.0/cmd/jaeger">Examples of Jaeger configuration files.</a></p><p>[3] <a href="https://prometheus.io/docs/prometheus/latest/getting_started/">https://prometheus.io/docs/prometheus/latest/getting_started/</a></p><p>[4] <a href="https://grafana.com/grafana/download?pg=oss-graf&amp;plcmt=resources&amp;platform=docker">https://grafana.com/grafana/download?pg=oss-graf&amp;plcmt=resources&amp;platform=docker</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0098a22b7c37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing the Conciliator Architecture for AI Agents in LangGraph]]></title>
            <link>https://medium.com/@juanluis1702/introducing-the-conciliator-architecture-for-ai-agents-in-langgraph-4a112a4daba8?source=rss-9ed3edbf79ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a112a4daba8</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[conciliator-architecture]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <dc:creator><![CDATA[Juan-Luis García-Mendoza]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 17:12:05 GMT</pubDate>
            <atom:updated>2025-04-05T17:12:05.036Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding AI Agents</h3><p><strong>AI Agents</strong> are revolutionizing the way we interact with Large Language Models (LLMs). It’s no longer just about generating text from a prompt; it’s about creating autonomous systems capable of reasoning, making decisions, and executing tasks intelligently.</p><p>AI agents are autonomous systems designed to perform tasks, make decisions, and interact with their environment. Unlike a static chatbot, an AI Agent <strong>reasons, leverages tools, and learns from context</strong> to achieve defined objectives.</p><p>These agents can operate independently or within a system of multiple agents, collaborating to achieve a goal. Examples include retrieval-augmented generation (RAG) systems, recommendation engines, and workflow automation bots. When multiple agents work together, coordination becomes a key challenge. Traditional architectures often rely on strict hierarchies or predefined workflows, limiting adaptability. To address this, frameworks like <a href="https://langchain-ai.github.io/langgraph/"><strong>LangGraph</strong> </a>have emerged, allowing for more flexible multi-agent systems.</p><h3>What is <a href="https://langchain-ai.github.io/langgraph/">LangGraph</a>?</h3><p><a href="https://langchain-ai.github.io/langgraph/"><strong>LangGraph</strong> </a>is a framework designed for managing multi-agent workflows within AI applications. Built on <a href="https://python.langchain.com/docs/introduction/"><strong>LangChain</strong></a>, it provides a graph-based structure for defining agent interactions. By leveraging <a href="https://langchain-ai.github.io/langgraph/"><strong>LangGraph</strong></a>, developers can model complex agent behaviors, ensuring efficient task execution, data flow, and decision-making. Additionally, its modular approach enables scalable AI systems, seamless coordination between multiple agents, and enhanced adaptability to dynamic tasks.</p><p><strong>Why Use </strong><a href="https://langchain-ai.github.io/langgraph/"><strong>LangGraph </strong></a><strong>for AI Agents?</strong></p><ul><li><strong>Flexible Agent Interactions</strong>: Define how agents communicate dynamically.</li><li><strong>Graph-Based Execution</strong>: Control workflows efficiently with nodes and edges.</li><li><strong>Support for Multi-Agent Coordination</strong>: Build systems where agents collaborate without bottlenecks.</li><li><strong>Scalability</strong>: Manage multiple agents efficiently in a structured yet adaptable way.</li></ul><h3>Common Multi-Agent Architectures in <a href="https://langchain-ai.github.io/langgraph/">LangGraph</a></h3><p>There are several ways to connect agents in a multi-agent system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9aRcoBfUgc1w5j1LdJ3Jg.png" /><figcaption>Multi-agent architectures (extracted from <a href="https://langchain-ai.github.io/langgraph/concepts/multi_agent/#multi-agent-architectures">LangGraph official site</a>)</figcaption></figure><p>While these architectures work well in structured environments, they may not be ideal for <strong>iterative collaboration and conflict resolution</strong>. This is where the <strong>Conciliator Architecture</strong> comes in.</p><h3>Conciliator Architecture: A New Approach to AI Agent Coordination</h3><p><strong>Conciliator Architecture</strong> is an iterative multi-agent framework where direct communication occurs between two (or possibly more) agents without a supervision. When no agreement is reached, a <strong>Conciliator Agent</strong> intervenes to resolve the conflict and make the final decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*d7Vag3mNrglVutzyqQQIYg.png" /></figure><h4>Key Advantages</h4><ul><li><strong>Iterative Refinement</strong>: Ensures high-quality outputs by enabling multiple revision cycles.</li><li><strong>Dynamic Resolution</strong>: The Conciliator intervenes only when needed, preventing endless loops.</li><li><strong>Balanced Autonomy</strong>: Agents interact freely while maintaining a structured decision-making process.</li><li><strong>No Extra Supervision:</strong> Direct communication between agents is possible without the need for an additional supervisor agent, simplifying the workflow.</li></ul><h4><strong>Conciliator Architecture vs Supervisor Architecture</strong></h4><p>Next, we will compare the Conciliator and Supervisor architectures because they share key similarities: both involve multiple agents collaborating on a task, have one agent making the final decisions, and are designed to structure agent coordination.</p><p><strong>Supervisor Architecture</strong></p><p><strong>Pros:</strong></p><ul><li><strong>Centralized control</strong>: Ensures clear and structured decision-making.</li><li><strong>Fewer conflicts</strong>: Reduces disagreements since the supervisor dictates the rules.</li><li><strong>Easier debugging</strong>: The hierarchical flow makes it simpler to track errors and improve efficiency.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Less flexibility</strong>: Agents cannot correct decisions made by the supervisor.</li><li><strong>No iterative improvement</strong>: Does not allow multiple revision rounds before making a decision.</li><li><strong>Computational bottleneck</strong>: The supervisor can become a performance bottleneck if managing too many agents.</li></ul><p><strong>Conciliator Architecture</strong></p><p><strong>Pros:</strong></p><ul><li><strong>More autonomy and flexibility</strong>: Agents collaborate freely without constant supervision.</li><li><strong>Higher quality results</strong>: Multiple iterations ensure a refined final output.</li><li><strong>Reduced single-point failure</strong>: The system does not rely on a single decision-maker for every step.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Risk of infinite loops</strong>: Without a defined iteration limit, agents could get stuck in endless reviews.</li><li><strong>More complex coordination</strong>: Requires clear rules on when the Conciliator should intervene.</li><li><strong>Variable computational cost</strong>: Resource usage can fluctuate depending on the number of iterations before conciliation.</li></ul><p><strong>Which One to Choose?</strong></p><ul><li>If you need full control and predictable efficiency → Supervisor Architecture</li><li>If you want flexibility and iterative refinement → Conciliator Architecture</li></ul><h4><strong>Examples of this architecture</strong></h4><p><strong>Content Editing &amp; Review</strong></p><p>This example showcases a <strong>conciliator agent-based architecture</strong> for an automated <strong>content editing and review workflow</strong>, applied to <strong>previously provided text</strong>. The system is designed to iteratively improve the content, ensuring clarity, coherence, and correctness, while leveraging a complete history of edits and reviews.</p><p>The full example is <a href="https://github.com/juanluis17/medium-blog/blob/main/llm_workflows/conciliator/content_editor.ipynb">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*D-7RW0D8zKDQKS-cmQdFQg.png" /></figure><p>The architecture consists of three specialized agents working collaboratively:</p><ul><li><strong>Reviewer Agent:</strong> Evaluate the current version of the text for clarity, coherence, and correctness. Assign a binary score (“yes” or “no”) and provide detailed and constructive feedback.</li></ul><pre>REVIEWER_PROMPT=&quot;&quot;&quot;You are an expert reviewer. Your task is to evaluate the \<br>following text based on clarity, coherence, and correctness. <br><br>### Task Instructions:<br>- Assign a Binary Score:<br>    - &quot;yes&quot; if the text meets all conditions.<br>    - &quot;no&quot; otherwise.<br>- Provide constructive feedback and suggest improvements. <br>- If the text is already perfect, say &#39;No changes needed&#39;<br>- Consider the Complete History:<br>    - Review the complete history provided below.<br>    - Understand the evolution and reasoning behind each change.<br>    - Pay close attention to recurring issues and how they have been addressed.<br>    - If you disagree with any of the decisions made, provide a clear explanation of your concerns.<br><br>**Text**:<br>{text}<br><br>**History:**<br>{history}<br>&quot;&quot;&quot;</pre><ul><li><strong>Editor Agent:</strong> Refines the text based on the Reviewer’s feedback, maintaining the original intent and avoiding previously identified errors.</li></ul><pre>EDITOR_PROMPT=&quot;&quot;&quot;You are an expert editor. Based on the reviewer&#39;s \<br>feedback, refine the original text accordingly. Ensure that all suggested \<br>improvements are implemented while maintaining the original intent.<br><br>### Task Instructions:<br>- Consider the reviewer&#39;s feedback:<br>    - The information provided in History is a detailed history of previous iterations of edition.<br>    - Each iteration includes the edited text along with feedback from either the reviewer or the editor.<br>    - Use this history to understand the evolution of the edition and to avoid repeating past errors.<br>    - Pay special attention to recurring issues identified by the reviewer.<br>- Edit the Text to align with the reviewer&#39;s feedback.<br>- Provide an explanation of the changes made.<br><br>**Text**:<br>{text}<br><br>**History:**<br>{history}<br>&quot;&quot;&quot;</pre><ul><li><strong>Conciliator Agent:</strong> Resolves any disagreements between <strong>Reviewer </strong>and <strong>Editor</strong>, making <strong>final decisions</strong> with clear justifications and ensuring that the resulting text meets high-quality standards.</li></ul><pre>CONCILIATOR_PROMPT=&quot;&quot;&quot;You are an expert Conciliator, tasked with resolving \<br>discrepancies between an Editor and a Reviewer in an editing workflow. \<br>Your goal is to analyze their interaction history and provide a definitive \<br>resolution that ensures the final text is clear, coherent, and correct.<br><br>### Task Instructions:<br>- Analyze the provided history and identify the key points of disagreement.<br>- Provide a definitive resolution for each disputed segment.<br>- Justify your decisions with clear and detailed explanations.<br>- Ensure that the final text maintains clarity, coherence, and correctness.<br>- Provide a summary of the reasoning in the ``explanation`` key.<br><br>**Original Text**:<br>{text}<br><br>**History:**<br>{history}<br>&quot;&quot;&quot;</pre><p><strong>Graph</strong></p><pre>workflow = StateGraph(WorkflowState)<br><br>workflow.add_node(&quot;reviewer&quot;, node_reviewer)<br>workflow.add_node(&quot;editor&quot;, node_editor)<br>workflow.add_node(&quot;conciliator&quot;, node_conciliator)<br><br><br>workflow.add_edge(START, &quot;reviewer&quot;)<br>workflow.add_conditional_edges(<br>  &quot;reviewer&quot;,<br>  lambda state: &quot;conciliator&quot; if state.iterations &gt;= state.max_iterations else END if state.history[-1].result == &quot;yes&quot; else &quot;editor&quot;  <br>)<br>workflow.add_edge(&quot;editor&quot;, &quot;reviewer&quot;)<br>workflow.add_edge(&quot;conciliator&quot;, END)<br><br>graph = workflow.compile()</pre><p>The process is managed through a <strong>state graph</strong>, which defines the sequence of actions and conditions for transitioning between agents. The workflow allows multiple iterations of review and editing until the text is approved or the maximum number of iterations is reached. By incorporating the full history of edits and reviews, this <strong>conciliator-based architecture</strong> enables a thoughtful, context-aware editorial process that delivers consistent and reliable results.</p><h4>Other examples</h4><p><strong>Legal Document Drafting</strong></p><ul><li><strong>Legal Research Agent:</strong> Collects relevant case law and legal references.</li><li><strong>Drafting Agent:</strong> Writes a legal document based on the research.</li><li><strong>Conciliator Agent:</strong> Mediates when the <strong>Research</strong> and <strong>Drafting</strong> agents disagree on how to frame legal arguments.</li></ul><p><strong>Code Generation &amp; Optimization</strong></p><ul><li><strong>Code Generator Agent:</strong> Writes an initial piece of code.</li><li><strong>Code Optimizer Agent:</strong> Refines it for performance and efficiency.</li><li><strong>Conciliator Agent:</strong> Resolves conflicts if the optimizer suggests changes that alter functionality.</li></ul><h3>Conclusion</h3><p>The <strong>Conciliator Architecture</strong> provides a structured yet flexible alternative to traditional agent models. By integrating <strong>iterative feedback and supervised resolution</strong>, it enhances collaboration in multi-agent systems. As AI workflows become more sophisticated, adopting such hybrid approaches will be crucial for achieving more reliable and human-like decision-making.</p><p>Are you ready to implement the Conciliator Architecture in your AI projects? Let’s discuss in the comments!</p><p>If you enjoy this content and want to support my work, feel free to buy me a coffee! ☕️<a href="https://buymeacoffee.com/juanluis1702">Buy Me a Coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a112a4daba8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Jaeger, Prometheus and Grafana with Docker Compose]]></title>
            <link>https://medium.com/@juanluis1702/deploying-jaeger-prometheus-and-grafana-with-docker-compose-87d3bd499bbe?source=rss-9ed3edbf79ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/87d3bd499bbe</guid>
            <category><![CDATA[grafana-dashboard]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[jaegertracing]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Juan-Luis García-Mendoza]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 14:43:14 GMT</pubDate>
            <atom:updated>2025-03-16T14:43:14.594Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explain how to deploy a monitoring and distributed tracing solution using <a href="https://www.jaegertracing.io/"><strong>Jaeger</strong></a>, <a href="https://prometheus.io/"><strong>Prometheus </strong></a>and <a href="https://grafana.com/"><strong>Grafana</strong></a>. We will use <strong>Docker Compose</strong> to manage the infrastructure in a simple and reproducible way.</p><h4>Introduction</h4><p>The stack we will deploy consists of the following components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*sVPaXB9vM3aWdhuEzl2wdg.png" /><figcaption>Monitoring Architecture with Jaeger, Prometheus and Grafana.</figcaption></figure><ul><li><a href="https://www.jaegertracing.io/"><strong>Jaeger</strong></a>: Jaeger is an open-source distributed tracing system used for monitoring and troubleshooting complex micro-services architectures. It traces requests as they flow through multiple services, visualizing dependencies and identifying performance bottlenecks or errors. This allows developers to optimize performance, quickly detect problems, and gain detailed insights into their distributed systems.</li><li><a href="https://prometheus.io/"><strong>Prometheus</strong></a>: Prometheus is an open-source monitoring and alerting toolkit. It collects time-series metrics from applications and systems, storing them in a time-series database. Thanks to its powerful query language, Prometheus enables comprehensive analysis of these metrics. Teams use Prometheus to monitor the health and performance of their applications, configure threshold-based alerts, and visualize data using dashboards. It is an essential tool for observability in micro-services and distributed systems environments.</li><li><a href="https://grafana.com/"><strong>Grafana</strong></a>: Grafana is an open-source visualization platform that allows you to create interactive and customizable dashboards for monitoring and analyzing data from various sources. It integrates seamlessly with time-series databases like Prometheus, as well as other monitoring systems. Grafana makes it easy to create clear and concise visualizations of metrics, logs, and traces, helping teams better understand the performance of their applications and systems.</li></ul><h4><strong>Repository and Source Code</strong></h4><p>You can find the full source code and configuration files in the <a href="https://github.com/juanluis17/medium-blog/tree/main/observability/simple">GitHub repository</a>. Feel free to clone, contribute, or open issues if you have any questions!</p><h4>Docker Compose Explained</h4><ol><li><strong>Jaeger</strong></li></ol><pre>jaeger:<br>    networks:<br>      backend:<br>        aliases: [ spm_metrics_source ]<br>    image: jaegertracing/jaeger:${JAEGER_VERSION:-latest}<br>    restart: always<br>    environment:<br>      - OTEL_ENABLED=true<br>    volumes:<br>      - &quot;./jaeger-ui.json:/etc/jaeger/jaeger-ui.json&quot;<br>      - &quot;./config.yml:/etc/jaeger/config.yml&quot;<br>    command: [&quot;--config&quot;, &quot;/etc/jaeger/config.yml&quot;]<br>    ports:<br>      - &quot;0.0.0.0:16686:16686&quot;<br>      - &quot;0.0.0.0:8888:8888&quot;<br>      - &quot;0.0.0.0:8889:8889&quot;<br>      - &quot;0.0.0.0:4317:4317&quot; # OTLP gRPC<br>      - &quot;0.0.0.0:4318:4318&quot; # OTLP HTTP</pre><p>To configure <strong>Jaeger</strong>, it is essential to set OTEL_ENABLED=true to enable receiving traces from OpenTelemetry-instrumented applications. Ports <strong>4317 (gRPC)</strong> and <strong>4318 (HTTP)</strong> must be exposed to receive trace data, while port <strong>16686 </strong>provides access to the Jaeger web interface to view collected traces.</p><p><strong>2. Prometheus</strong></p><pre>  prometheus:<br>    networks:<br>      - backend<br>    image: prom/prometheus:v3.1.0<br>    restart: always<br>    volumes:<br>      - &quot;./prometheus.yml:/etc/prometheus/prometheus.yml&quot;<br>    ports:<br>      - &quot;9090:9090&quot;</pre><p>Defining the configuration via a <strong>volume</strong> allows Prometheus customization without rebuilding the image. A simple Docker restart loads the updated configuration, including scrape settings and alerting rules. Exposing <strong>port 9090</strong> provides access to Prometheus web interface at http://&lt;host_ip&gt;:9090, allowing users to query metrics, view graphs, and manage Prometheus.</p><p><strong>3. Grafana</strong></p><pre>  grafana:<br>    image: grafana/grafana:latest<br>    restart: always<br>    networks:<br>      - backend<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      - GF_SECURITY_ADMIN_PASSWORD=admin<br>    depends_on:<br>      - prometheus</pre><p>Exposing <strong>port 3000</strong> provides access to Grafana web interface at http://&lt;host_ip&gt;:3000. The GF_SECURITY_ADMIN_PASSWORD environment variable sets the initial admin password. In production environments, this should be replaced with a strong, secure password.</p><h4>Configuration Files</h4><ol><li><strong>prometheus.yml</strong></li></ol><pre>global:<br>  scrape_interval: 60s<br>  evaluation_interval: 60s<br><br>scrape_configs:<br>  - job_name: &#39;spm-metrics&#39;<br>    metrics_path: &#39;/metrics&#39;<br>    static_configs:<br>      - targets: [&#39;spm_metrics_source:8889&#39;]</pre><p>The <strong>global</strong> section in Prometheus sets configuration options, with scrape_interval: 60s and evaluation_interval: 60s defining how often Prometheus scrapes metrics and evaluates alerting rules. The <strong>scrape_configs</strong> section specifies where Prometheus retrieves metrics and the <strong>job_name &#39;spm-metrics&#39;</strong> identifies this job. Metrics are collected from /metrics, which means Prometheus will query http://&lt;target_address&gt;/metrics. The <strong>targets</strong> field (spm_metrics_source:8889) points to the service providing metrics, which, due to Docker Compose alias, resolves to the <strong>Jaeger container</strong>.</p><p><strong>2. config.yml</strong></p><pre>service:<br>  extensions: [jaeger_storage, jaeger_query]<br>  pipelines:<br>    traces:<br>      receivers: [otlp]<br>      processors: [batch]<br>      exporters: [jaeger_storage_exporter, spanmetrics]<br>    metrics/spanmetrics:<br>      receivers: [spanmetrics]<br>      exporters: [prometheus]<br>  telemetry:<br>    resource:<br>      service.name: jaeger<br>    metrics:<br>      level: detailed<br>      readers:<br>        - pull:<br>            exporter:<br>              prometheus:<br>                host: 0.0.0.0<br>                port: 8888<br>    logs:<br>      level: DEBUG<br><br>extensions:<br>  jaeger_query:<br>    storage:<br>      traces: some_storage<br>      metrics: some_metrics_storage<br>  jaeger_storage:<br>    backends:<br>      some_storage:<br>        memory:<br>          max_traces: 100000<br>    metric_backends:<br>      some_metrics_storage:<br>        prometheus:<br>          endpoint: http://prometheus:9090<br>          normalize_calls: true<br>          normalize_duration: true<br><br>connectors:<br>  spanmetrics:<br><br>receivers:<br>  otlp:<br>    protocols:<br>      grpc:<br>        endpoint: &quot;0.0.0.0:4317&quot;<br>      http:<br>        endpoint: &quot;0.0.0.0:4318&quot;<br><br>processors:<br>  batch:<br><br>exporters:<br>  jaeger_storage_exporter:<br>    trace_storage: some_storage<br>  prometheus:<br>    endpoint: &quot;0.0.0.0:8889&quot;</pre><p>This <strong>OpenTelemetry Collector</strong> configuration enables the reception, processing, and export of traces and metrics using <strong>Jaeger</strong> and <strong>Prometheus</strong>. Traces are received from OpenTelemetry-instrumented applications via the <strong>OTLP protocol</strong>, listening on <strong>ports 4317 (gRPC)</strong> and <strong>4318 (HTTP)</strong>. These traces are processed in <strong>batches</strong> for efficiency and then exported to <strong>Jaeger</strong> using jaeger_storage_exporter, while metrics derived from the traces are sent to <strong>Prometheus </strong>using the spanmetrics connector. For storage management, the jaeger_storage extension configures an in-memory backend capable of storing up to <strong>100,000 traces</strong>, while jaeger_query enables querying of stored traces and metrics. For metrics reception, the spanmetrics connector converts traces into metrics for Prometheus to collect, with the collector’s own metrics exposed on <strong>port 8888</strong>. The batch processor aggregates and processes the data before exporting it, thereby optimizing system performance. The telemetry configuration defines a <strong>&quot;detailed&quot;</strong> level better observability, while <strong>DEBUG-level logs</strong> facilitate troubleshooting. In short, this configuration provides a robust solution for capturing traces, storing them in <strong>Jaeger</strong>, converting them into metrics, and monitoring them in <strong>Prometheus</strong>, ensuring comprehensive observability in distributed environments.</p><h4>Deployment with Docker Compose</h4><p>To start the containers, run:</p><pre>sudo docker-compose up -d</pre><p><strong>Verifying Services</strong></p><ul><li><strong>Jaeger UI</strong>: <a href="http://localhost:16686/">http://localhost:16686</a></li><li><strong>Prometheus</strong>: <a href="http://localhost:9090/">http://localhost:9090</a></li><li><strong>Grafana</strong>: <a href="http://localhost:5602/">http://localhost:</a>3000 (User: admin, Password: admin)</li></ul><p><strong>Creating Dashboards in Grafana</strong></p><p>Once the stack is running, you can create <strong>custom dashboards</strong> in Grafana that integrate data from <strong>Prometheus and Jaeger</strong>. Simply add Prometheus as a data source to visualize metrics and Jaeger to analyze traces, enabling a complete monitoring and observability setup.</p><h4>Conclusion</h4><p>In this article, we successfully deployed a full observability stack using <strong>Jaeger</strong>, <strong>Prometheus </strong>and <strong>Grafana </strong>with Docker Compose. This setup provides a powerful and scalable solution for distributed tracing, monitoring, and data visualization.</p><p>This deployment allows teams to <strong>gain detailed insights into their applications, detect issues early, and optimize performance</strong> with minimal setup effort. Whether managing micro-services, troubleshooting latency issues, or ensuring system reliability, this observability stack is a solid foundation for improving visibility into your infrastructure.</p><h4>References</h4><p>[1] <a href="https://www.jaegertracing.io/docs/2.4/deployment/">Jaeger Deployment.</a></p><p>[2] <a href="https://github.com/jaegertracing/jaeger/tree/v2.4.0/cmd/jaeger">Examples of Jaeger configuration files.</a></p><p>[3] <a href="https://prometheus.io/docs/prometheus/latest/getting_started/">https://prometheus.io/docs/prometheus/latest/getting_started/</a></p><p>[4] <a href="https://grafana.com/grafana/download?pg=oss-graf&amp;plcmt=resources&amp;platform=docker">https://grafana.com/grafana/download?pg=oss-graf&amp;plcmt=resources&amp;platform=docker</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87d3bd499bbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unbabel’s LLM Tower: How to deploy the model locally.]]></title>
            <link>https://medium.com/@juanluis1702/unbabels-llm-tower-how-to-deploy-the-model-locally-54f2cb4f87d7?source=rss-9ed3edbf79ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/54f2cb4f87d7</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[llm-tower]]></category>
            <category><![CDATA[text-generation-inference]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-translation]]></category>
            <dc:creator><![CDATA[Juan-Luis García-Mendoza]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 13:46:50 GMT</pubDate>
            <atom:updated>2024-02-16T19:32:30.207Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deploying Unbabel’s LLM Tower locally using <strong>Text Generation Inference</strong></h4><h4>What is Unbabel’s LLM Tower?</h4><p><a href="https://unbabel.com/announcing-tower-an-open-multilingual-llm-for-translation-related-tasks/">Tower</a> is a multilingual 7B parameter Large Language Model (LLM) optimized for translation-related tasks [1]. <a href="https://unbabel.com/announcing-tower-an-open-multilingual-llm-for-translation-related-tasks/">Tower</a> was released by Unbabel in collaboration with the SARDINE Lab at Instituto Superior Técnico, and the MICS lab at CentraleSupélec at the University of Paris-Saclay. It’s built on top of Llama 2 [2] and is optimized for translation-related tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gfp3ElK41MQCyFkf_cd73A.png" /><figcaption>Fine-tuning process of Tower (extracted from [1]).</figcaption></figure><p><strong>Languages included.</strong> Tower includes 10 languages: English, German, French, Spanish, Chinese, Portuguese, Italian, Russian, Korean, and Dutch.</p><p><strong>State-of-the-art models on translation: </strong>It matches models on translation as well as GPT3.5 [3], and it surpasses larger open models, such as ALMA 13B [4] and LLaMA-2 70B [2].</p><p>The authors released the following elements:</p><ul><li>Weights of their two Tower models: <a href="https://huggingface.co/Unbabel/TowerBase-7B-v0.1"><strong>TowerBase</strong></a> and <a href="https://huggingface.co/Unbabel/TowerInstruct-7B-v0.1"><strong>TowerInstruct</strong></a>.</li><li>Data that they used to fine-tune these models: <a href="https://huggingface.co/datasets/Unbabel/TowerBlocks-v0.1"><strong>TowerBlocks</strong></a></li><li>Evaluation data and code: <a href="https://github.com/deep-spin/tower-eval"><strong>TowerEval</strong></a><strong>.</strong></li></ul><h4>Deploying Unbabel’s LLM Tower locally using <a href="https://github.com/huggingface/text-generation-inference">Text Generation Inference</a></h4><blockquote>Text Generation Inference (TGI) is a toolkit for deploying and serving Large Language Models (LLMs). TGI enables high-performance text generation for the most popular open-source LLMs, including Llama, Falcon, StarCoder, BLOOM, GPT-NeoX, and <a href="https://huggingface.co/docs/text-generation-inference/supported_models">more</a>.</blockquote><p>If you want to use NVIDIA GPUs, you need to install the <a href="https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html">NVIDIA Container Toolkit</a>. Hugging Face recommends NVIDIA drivers with CUDA version 12.2 or higher.</p><p>You can deploy Unbabel’s LLM Tower (Instruct version of the model) locally on 1x A10G (24GB) with Text Generation Inference and Docker as follows:</p><pre>docker run -p 8080:80 --gpus all --shm-size 1g -v data:/data \ <br>       ghcr.io/huggingface/text-generation-inference:1.3 \<br>       --model-id Unbabel/TowerInstruct-7B-v0.1</pre><p>The model without any quantization uses about 18Gb of VRAM.</p><p>If you want deploy the base model, just change the parameter <em>model-id</em> to “Unbabel/TowerBase-7B-v0.1”</p><h4>Prompt Format</h4><p>TowerInstruct-v0.1 use the following prompt template:</p><pre>&lt;|im_start|&gt;user<br>{USER PROMPT}&lt;|im_end|&gt;<br>&lt;|im_start|&gt;assistant<br>{MODEL RESPONSE}&lt;|im_end|&gt;<br>&lt;|im_start|&gt;user<br>[...]</pre><h4>Inference</h4><p>You can generate responses by making requests to the model. For example:</p><pre>curl 127.0.0.1:8080/generate -X POST \<br>     -d &#39;{&quot;inputs&quot;:&quot;&lt;|im_start|&gt;user\nTranslate the following text from Portuguese into English.\nPortuguese: Um grupo de investigadores lançou um novo modelo para tarefas relacionadas com tradução.\nEnglish:&lt;|im_end|&gt;&quot;}&#39; \<br>     -H &#39;Content-Type: application/json&#39;</pre><p>The output for this example is:</p><pre>{&quot;generated_text&quot;:&quot;\nA group of researchers has launched a new model for translation-related tasks.&quot;}</pre><h4>References</h4><p>[1] <a href="https://unbabel.com/announcing-tower-an-open-multilingual-llm-for-translation-related-tasks/">Announcing Tower: An Open Multilingual LLM for Translation-Related Tasks</a>.</p><p>[2] <a href="https://arxiv.org/abs/2307.09288">Llama 2: Open Foundation and Fine-Tuned Chat Models</a>. Technical report.</p><p>[3] <a href="https://platform.openai.com/docs/models/gpt-3-5">GPT-3.5</a></p><p>[4] <a href="https://arxiv.org/abs/2309.11674">A Paradigm Shift in Machine Translation: Boosting Translation Performance of Large Language Models</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54f2cb4f87d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Fine-Tune m2m-100 Model in fairseq?]]></title>
            <link>https://medium.com/@juanluis1702/how-to-fine-tune-m2m-100-model-in-fairseq-6670676ddf2b?source=rss-9ed3edbf79ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/6670676ddf2b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[m2m-model]]></category>
            <category><![CDATA[fairseq]]></category>
            <category><![CDATA[machine-translation]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Juan-Luis García-Mendoza]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 13:54:24 GMT</pubDate>
            <atom:updated>2024-01-21T12:03:54.324Z</atom:updated>
            <content:encoded><![CDATA[<h4>A detailed step-by-step example of how to fine-tune m2m-100 model in fairseq</h4><h4>What’s the m2m-100 model?</h4><p>The <strong>m2m-100</strong> model was proposed by Fan et al., (2021) in <a href="https://dl.acm.org/doi/abs/10.5555/3546258.3546365">Beyond English-Centric Multilingual Machine Translation</a>. Before this model, the translations between two languages were dependent on the English language. However, the <strong>m2m-100 model</strong> translates data from one language to another without using English as an intermediary. This makes it a true Many-to-Many multilingual translation model that can translate directly between any pair of 100 languages.</p><blockquote><em>Our focus on non-English-Centric models brings gains of more than 10 BLEU when directly translating between non-English directions while performing competitively to the best single systems of WMT (Fan et al., 2021).</em></blockquote><p>The <strong>m2m-100 model </strong>is based on the Transformer sequence-to-sequence architecture, which is composed of two modules: the encoder and the decoder (Vaswani et al., 2017). The encoder transforms the source token sequence into a sequence of embeddings of the same length. Then, the decoder sequentially produces the target sentence, token by token, or autoregressively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*DuWJOw_Ma74QFr3fI5JsEw.png" /><figcaption>Transformers architecture (source: Vaswani et al., 2017)</figcaption></figure><h4>Fine-Tune m2m-100 Model in fairseq</h4><p>This post is based in the <a href="https://github.com/facebookresearch/fairseq/tree/main/examples/m2m_100">m2m-100 example in fairseq</a>. This post utilizes the WMT’22 dataset.</p><p><strong>Preprocess Data</strong></p><p>To download the dataset, follow the below commands.</p><pre>sacrebleu -t wmt22 -l fr-de --echo src &gt; wmt22.fr<br>sacrebleu -t wmt22 -l fr-de --echo ref &gt; wmt22.de<br>paste wmt22.fr wmt22.de &gt; wmt22.fr.de</pre><p>After downloading raw data, you will need to process the data. You can use the preprocess scripts proposed in the <a href="https://github.com/facebookresearch/fairseq/tree/main/examples/m2m_100/process_data">m2m-100 example</a> or create your own scripts. Next, the data set must be divided into train, dev, and test partitions. In our case, we use the function <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html#sklearn.model_selection.train_test_split">train_test_split</a> from <a href="https://scikit-learn.org/stable/index.html">scikit-learn</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*MMS1HAcudGLZTDIO45gw-g.png" /><figcaption>Directory structure after splitting the dataset. The partitions were saved in the wmt22 folder.</figcaption></figure><p>Once the data has been processed and splitted, we must apply the Sentence Piece Model (SPM).</p><pre>#Download the model<br>wget https://dl.fbaipublicfiles.com/m2m_100/spm.128k.model<br><br>#Create the folder to save the SPM result<br>mkdir wmt22_spm<br><br>#Apply the model<br>#Train fr<br>python /path/to/fairseq/scripts/spm_encode.py \<br>    --model spm.128k.model \<br>    --output_format=piece \<br>    --inputs=wmt22/train.fr \<br>    --outputs=wmt22_spm/train.spm.fr<br>#Train de<br>python /path/to/fairseq/scripts/spm_encode.py \<br>    --model spm.128k.model \<br>    --output_format=piece \<br>    --inputs=wmt22/train.de \<br>    --outputs=wmt22_spm/train.spm.de<br>#Dev fr<br>python /path/to/fairseq/scripts/spm_encode.py \<br>    --model spm.128k.model \<br>    --output_format=piece \<br>    --inputs=wmt22/dev.fr \<br>    --outputs=wmt22_spm/dev.spm.fr<br>#Dev de<br>python /path/to/fairseq/scripts/spm_encode.py \<br>    --model spm.128k.model \<br>    --output_format=piece \<br>    --inputs=wmt22/dev.de \<br>    --outputs=wmt22_spm/dev.spm.de<br>#Test fr<br>python /path/to/fairseq/scripts/spm_encode.py \<br>    --model spm.128k.model \<br>    --output_format=piece \<br>    --inputs=wmt22/test.fr \<br>    --outputs=wmt22_spm/test.spm.fr<br>#Test de<br>python /path/to/fairseq/scripts/spm_encode.py \<br>    --model spm.128k.model \<br>    --output_format=piece \<br>    --inputs=wmt22/test.de \<br>    --outputs=wmt22_spm/test.spm.de</pre><p>Data binarization</p><pre>cd wmt22_spm<br><br>#Create the folder to save the binarize data<br>mkdir wmt22_bin<br><br>#Download the dictionary<br>wget https://dl.fbaipublicfiles.com/m2m_100/model_dict.128k.txt<br><br>#Fairseq Preprocess<br>python /path/to/fairseq/fairseq_cli/preprocess.py  \<br>    --source-lang fr \<br>    --target-lang de \<br>    --testpref spm.$src.$tgt \<br>    --thresholdsrc 0 \<br>    --thresholdtgt 0 \<br>    --destdir ./wmt22_bin \<br>    --srcdict model_dict.128k.txt \<br>    --tgtdict model_dict.128k.txt \<br>    --trainpref train.spm \<br>    --validpref dev.spm \<br>    --testpref  test.spm</pre><blockquote>IMPORTANT: Download model_dict.128k.txt instead of data_dict.128k.txt. In the fairseq example they use data_dict.128k.txt for the preprocess.py and then it gives error in the fine tuning.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*fd0zizWej-9OzJkqmGbsAQ.png" /><figcaption>Structure of wmt22_spm after SPM and binarization.</figcaption></figure><p><strong>Fine-Tuning the model</strong></p><pre>cd ..<br><br># 418M parameter model<br>wget https://dl.fbaipublicfiles.com/m2m_100/418M_last_checkpoint.pt <br><br>CUDA_VISIBLE_DEVICES=&quot;0&quot; python /path/to/fairseq/fairseq_cli/train.py ./wmt22_spm/wmt22_bin/ \<br>    --arch transformer_wmt_en_de_big \<br>    --task translation_multi_simple_epoch \<br>    --finetune-from-model ./418M_last_checkpoint.pt  \<br>    --save-dir ./checkpoints/ \<br>    --langs &#39;af,am,ar,ast,az,ba,be,bg,bn,br,bs,ca,ceb,cs,cy,da,de,el,en,es,et,fa,ff,fi,fr,fy,ga,gd,gl,gu,ha,he,hi,hr,ht,hu,hy,id,ig,ilo,is,it,ja,jv,ka,kk,km,kn,ko,lb,lg,ln,lo,lt,lv,mg,mk,ml,mn,mr,ms,my,ne,nl,no,ns,oc,or,pa,pl,ps,pt,ro,ru,sd,si,sk,sl,so,sq,sr,ss,su,sv,sw,ta,th,tl,tn,tr,uk,ur,uz,vi,wo,xh,yi,yo,zh,zu&#39; \<br>    --lang-pairs &#39;fr-de&#39; \<br>    --max-tokens 1200 \<br>    --encoder-normalize-before --decoder-normalize-before \<br>    --sampling-method temperature --sampling-temperature 1.5 \<br>    --encoder-langtok src --decoder-langtok \<br>    --criterion label_smoothed_cross_entropy --label-smoothing 0.2 \<br>    --optimizer adam --adam-eps 1e-06 --adam-betas &#39;(0.9, 0.98)&#39; \<br>    --lr-scheduler inverse_sqrt --lr 3e-05 \<br>    --warmup-updates 2500 --max-update 40000 \<br>    --dropout 0.3 --attention-dropout 0.1 \<br>    --weight-decay 0.0 \<br>    --update-freq 2 --save-interval 5 \<br>    --save-interval-updates 5000 --keep-interval-updates 3 \<br>    --no-epoch-checkpoints \<br>    --seed 222 \<br>    --log-format simple \<br>    --log-interval 2 \<br>    --encoder-layers 12 --decoder-layers 12 \<br>    --encoder-layerdrop 0.05 --decoder-layerdrop 0.05 \<br>    --share-decoder-input-output-embed \<br>    --share-all-embeddings \<br>    --ddp-backend no_c10d</pre><p><strong>Generation</strong></p><pre>python /path/to/fairseq/fairseq_cli/generate.py ./wmt22_spm/wmt22_bin/  \<br>    --max-tokens 2000  \<br>    --batch-size 1  \<br>    --path ./checkpoints/checkpoint_best.pt  \<br>    --fixed-dictionary ./wmt22_spm/model_dict.128k.txt \<br>    -s fr -t de  \<br>    --remove-bpe &#39;sentencepiece&#39;  \<br>    --beam 5  \<br>    --task translation_multi_simple_epoch  \<br>    --lang-pairs &#39;fr-de&#39;  \<br>    --decoder-langtok \<br>    --encoder-langtok src \<br>    --gen-subset test  \<br>    --dataset-impl mmap \<br>    --distributed-world-size 1 \<br>    --distributed-no-spawn  </pre><p><strong>References</strong></p><p>Fan, A., Bhosale, S., Schwenk, H., Ma, Z., El-Kishky, A., Goyal, S., … &amp; Joulin, A. (2021). Beyond english-centric multilingual machine translation. <em>The Journal of Machine Learning Research</em>, <em>22</em>(1), 4839–4886.</p><p><a href="https://github.com/facebookresearch/fairseq/tree/main/examples/m2m_100">https://github.com/facebookresearch/fairseq/tree/main/examples/m2m_100</a></p><p>Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … &amp; Polosukhin, I. (2017). Attention is all you need. <em>Advances in neural information processing systems</em>, <em>30</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6670676ddf2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>