<?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 Leonardo Benitez on Medium]]></title>
        <description><![CDATA[Stories by Leonardo Benitez on Medium]]></description>
        <link>https://medium.com/@lsbenitezpereira?source=rss-7dd1d19bcaa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qnzA4YwJjmoXSJjt</url>
            <title>Stories by Leonardo Benitez on Medium</title>
            <link>https://medium.com/@lsbenitezpereira?source=rss-7dd1d19bcaa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:33:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lsbenitezpereira/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[Policy-as-Code Is Real Progress, Just Not the Progress You Think]]></title>
            <link>https://medium.com/@lsbenitezpereira/policy-as-code-is-real-progress-just-not-the-progress-you-think-38345bd8b780?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/38345bd8b780</guid>
            <category><![CDATA[oscal]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[shift-left-security]]></category>
            <category><![CDATA[compliance-ops]]></category>
            <category><![CDATA[policy-as-code]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Thu, 07 May 2026 20:38:39 GMT</pubDate>
            <atom:updated>2026-05-07T21:04:20.489Z</atom:updated>
            <content:encoded><![CDATA[<p>Compliance tooling vendors have spent years selling the idea that you can shift compliance left into the CI pipeline the way you shifted security tests, and that doing so will solve some meaningful share of the audit pain. Some of that is true. Most of it is overstated, and the part that is overstated is the part that gets the marketing budget.</p><p>Only 13% of organizations are running compliance-as-code in any meaningful sense [1]. More than half still rely entirely on manual processes. Most vendor content about shift-left compliance is aimed at the 87% — aspirational marketing dressed as case studies.</p><p>This article is the long version of an argument I have been making in pieces: policy-as-code solves a narrow but real class of problems; auditors care far more about operational evidence than CI checks; a large class of compliance requirements is uncodifiable in principle, not just in practice; and despite all that, you can build something useful if you are honest about what each layer of your stack actually does. I will close on a reference architecture I have been working on — <a href="https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot">compliance-ops-bedrock</a> [19] — that takes its own limitations seriously. The repository has more detail than I cover here; this article is about the reasoning behind the design choices, not the implementation walkthrough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3Nr6rO_4pPvjHqbE1Ocqw.png" /></figure><blockquote><strong>A note on how this was written:</strong> this article was largely produced with AI assistance, with me acting as the reviewer, editor, and final arbiter on substance. I read every claim, removed the ones I could not stand behind, and added the ones the model would not have made on its own. If something here is wrong, that’s on me.</blockquote><h3>What Policy-as-Code Actually Solves</h3><p>The core idea is simple: express a compliance control as a machine-evaluable rule, then check every infrastructure change against that rule before it reaches production. A Terraform file that opens port 22 to the world fails the pipeline. An S3 bucket without encryption at rest fails the pipeline. A Kubernetes pod running as root fails the pipeline.</p><p>Tools like Open Policy Agent (OPA), Checkov, and tfsec do this well. The feedback loop — from configuration change to compliance signal — compresses from weeks (audit cycle) to seconds (CI check) [5]. That compression has economic value, and it has made a generation of security engineers measurably less miserable.</p><p>NIST’s OSCAL format [18] is the attempt to standardise how these controls are described, versioned, and exchanged between tools. With FedRAMP mandating machine-readable authorisation packages by September 2026, and Singapore’s GovTech adopting OSCAL for cross-agency standardisation, the format is gaining traction beyond its US federal origins. The OSCAL Foundation [7], launched in late 2025 with AWS, Cisco, Google, and RedHat on its advisory board, is a signal that the private sector is betting on this becoming infrastructure.</p><p>So far, this is the story you have already heard. The interesting part is where it stops working.</p><h3>The domain problem</h3><p>Policy-as-code works on things that can be stated as propositions about structured data. “Does this resource configuration contain property X with value Y?” is a question OPA can answer. Rego, OPA’s policy language, is essentially Prolog-derived logic programming over JSON documents.</p><p>Most of what compliance frameworks care about is not structured data about infrastructure configuration. GDPR Article 5 [13] requires data minimisation, purpose limitation, storage limitation, accuracy, integrity and confidentiality, and accountability. Every one of these is a principle requiring human judgment about organisational practice.</p><p>You cannot write a Rego rule that checks whether your organisation is collecting data “adequate, relevant and limited to what is necessary.” You can check whether a database schema has a created_at column and whether a deletion job is configured. Whether the data itself is necessary depends on your business model, your users, and your legal obligations. No CI pipeline touches this.</p><p>The same gap appears in SOC 2. The standard defines five Trust Services Criteria: security, availability, processing integrity, confidentiality, and privacy. Technical controls — access logging, encryption, vulnerability management — are automatable. Organisational controls are not. The list of common SOC 2 audit failures from Linford &amp; Company [3] is revealing: poor asset inventory, lack of separation of duties, subservice organisations not monitored, internal controls not monitored. These are process failures, not configuration failures. There is no CI check for “does your organisation actually monitor its third-party vendors in practice.”</p><h3>The DSL problem</h3><p>Even within its domain, policy-as-code has a usability problem the community tends to underplay.</p><p>Rego is the obvious example — Permit.io’s article “Everyone Loves Policy as Code, No One Wants to Write Rego” [4] is an accurate description of the adoption barrier rather than a criticism of the tool. But the pattern is broader. Sentinel (HashiCorp), Cedar (AWS), CUE-based policy languages, the various YAML-DSL hybrids in cloud-native tooling — all of them ask the developer to learn a new mental model, and all of them are essentially inaccessible to the compliance professionals who actually own the controls being encoded.</p><p>The structural problem is the translation layer. The compliance officer who knows what controls need to exist cannot write the policies. The developer who can write the policies does not always understand the regulatory requirement they are implementing. Organisations either hire expensive specialists to bridge the gap or, more commonly, skip the exercise.</p><p>Some tools try to solve this with higher-level abstractions — friendlier DSLs, natural-language rule builders, GUI-based policy editors. Those abstractions have their own failure mode: a developer writes a policy in the friendly layer, it looks right, but the underlying logic does not match what the compliance officer required. Misalignments hide there until an auditor finds them.</p><h3>The multi-cloud problem</h3><p>For organisations running across AWS, Azure, and GCP — which is most large enterprises — policy-as-code faces a coherence problem that is rarely discussed honestly [6].</p><p>Each cloud provider has its own policy primitives. AWS has SCPs, GuardDuty, Config Rules. Azure has Policy. GCP has Organization Policy. Each has its own configuration format, event model, and coverage gaps. Writing a control once and enforcing it consistently across all three requires abstraction layers — Terraform’s provider model, or tools like Pulumi — that add complexity and lag.</p><p>In practice, organisations end up with cloud-native policies that drift from each other, a compliance team that cannot audit cross-cloud state without serious tooling investment, and a CI pipeline that catches issues at code review but cannot see what was deployed three years ago. None of this is unsolvable. But “just use policy-as-code” does not solve it.</p><h3>What this means practically</h3><p>Policy-as-code is a necessary component of a modern compliance program. It is not sufficient. Organisations that treat it as sufficient pass their CI pipeline checks and then fail their SOC 2 audits because nobody documented access reviews for the last six months, or because the vendor management program existed only as a policy document nobody read [2].</p><p>The framing I would prefer: shift-left compliance shifts the detection of a specific class of infrastructure configuration errors earlier in the development cycle. That is valuable. It does not shift governance, process, culture, or judgment earlier in the development cycle. Those things cannot be shifted by writing more code.</p><h3>The Gap Between the Standard and the Room</h3><p>The next layer of the argument: what does a compliance audit actually look like in practice, and how does that differ from what the standards documentation implies? The picture from post-mortems, practitioner accounts, and audit firm guidance is not flattering for the compliance-as-code narrative.</p><h3>The auditor’s actual checklist</h3><p>When a GDPR auditor shows up — internal audit team or Supervisory Authority inspector — the first thing they want is the Record of Processing Activities (ROPA). Article 30 requires this, and it is the first document requested in virtually every audit described in published practitioner accounts [8][9].</p><p>The ROPA is not a technical document. It is a human-authored inventory: what data you collect, from whom, for what purpose, with what legal basis, shared with which processors, retained for how long, secured how. Producing it correctly requires interviews with business unit owners, review of procurement contracts, and legal analysis of purpose limitation. A perfectly configured S3 bucket with encryption at rest does nothing to produce this document.</p><p>After the ROPA, auditors typically want: data processing agreements with all processors and sub-processors, evidence of Data Protection Impact Assessments (DPIAs) for high-risk processing, records of how data subject rights requests were handled, and evidence of staff training. None of these are technical artifacts. All require ongoing human process.</p><p>The case that recurs in practitioner accounts is an organisation with excellent technical controls caught with unencrypted backups, incomplete data mapping, and missing vendor risk assessments. That is a documentation failure, not a configuration failure, and no static analysis tool catches it.</p><h3>“If it isn’t documented, it didn’t happen”</h3><p>This phrase — paraphrased the same way in nearly every audit post-mortem I read — is not a technical principle but an evidentiary one. Auditors are not assessing whether your system is secure. They are assessing whether your security controls exist, are documented, and are operating effectively as evidenced by records. These are related but not identical questions.</p><p>The most common SOC 2 audit failures, per Linford &amp; Company [3][10]:</p><ol><li><strong>Incomplete access reviews.</strong> Companies document quarterly access reviews as a control, complete two of four in a year, get flagged for a control exception.</li><li><strong>Asset inventory gaps.</strong> If you do not know what systems you have, you cannot document their security posture.</li><li><strong>Vendor management failures.</strong> Auditors enumerate every vendor with access to customer data — support tools, email delivery services, analytics platforms, payment processors, backup providers — and expect documented assessments of each.</li><li><strong>Separation of duties not maintained.</strong> The developer who deploys code should not be the same person who approves the change, and that needs to be demonstrably enforced, not just stated in policy.</li></ol><p>The common thread is process and governance. The companies in these cases had CI pipelines and policy-as-code tooling. The tooling did not catch that someone with production database access had not been reviewed for permission revocation when they changed roles. The tooling did not document vendor assessments. The tooling did not enforce who could approve a change management ticket.</p><h3>The Standard vs. The Room</h3><p>Every compliance standard I looked at has a similar structure: a set of principles, a set of controls implementing those principles, and an implied expectation that the auditor verifies control implementation through documentation and testing. The gap between what the standard specifies and what the auditor actually requests in the room runs in a consistent direction: auditors want evidence of consistent, documented process more than technical control sophistication.</p><p>An organisation that sends complete evidence packets — access review logs, change management tickets, training completion records, incident response test results — will fare better than one with a sophisticated policy-as-code pipeline but incomplete operational records. This is the part of the compliance industry that tooling vendors have no financial incentive to communicate.</p><p>ISO 27001 is structured the same way. The audit consists of a stage 1 audit (documentation review) and a stage 2 audit (implementation verification). Stage 1 is literally checking that your Information Security Management System documentation is complete and internally consistent. No amount of Terraform policy checking is relevant at stage 1. What matters is whether your information security policy is up to date, whether your risk register exists and is maintained, whether your Statement of Applicability is accurate.</p><h3>The human-centric controls problem</h3><p>The category of controls that are fundamentally about human behaviour and organisational culture is the most underappreciated part of compliance.</p><p>GDPR’s accountability principle (Article 5(2)) requires that organisations be able to demonstrate compliance. This is not just a documentation requirement — it is a cultural one. An organisation with complete documentation that does not actually practice what is documented will eventually fail. Employees who do not understand why they are doing what they are doing will not do it consistently. Vendors who are not actively managed drift out of compliance. Business units that treat the ROPA as a legal department problem will generate new data flows that never get documented.</p><p>LRN’s 2025 Ethics and Compliance Program Maturity study [11] found that only 31% of organisations formally evaluate ethical behaviour through performance reviews, and only 33% offer manager-specific training on tone from the middle. These are indicators of organisational culture, not technical controls. They predict compliance behaviour in ways no policy engine can.</p><p>The Dragnet Secure analysis of regulatory compliance and human error [12] puts it directly: well-trained employees gradually forget specific procedures over time. This is not a configuration management problem. It is a human cognitive problem. Training completion rates are a proxy, but proxies are not controls.</p><h3>What this should change about how compliance systems are built</h3><p>The implication for any OSCAL-based compliance infrastructure, including <a href="https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot">compliance-ops-bedrock</a> [19], is that the machine-readable control registry and the CI pipeline checks are necessary components, not the whole program.</p><p>A compliance program that passes real audits has at minimum three layers:</p><ol><li><strong>Technical controls with automated verification.</strong> Configuration checks, SAST, DAST, access logging, encryption enforcement. Automated evidence collection. This is where policy-as-code lives, and it works well here.</li><li><strong>Operational process controls with structured manual evidence.</strong> Access reviews, change management approvals, incident response tests, training completion, vendor assessments. These need scheduled reminders, human owners, documented outputs, a system of record. Versioned and signed. OSCAL’s assessment-results model can represent these, but someone still has to do the process.</li><li><strong>Cultural and governance controls.</strong> Accountability structures, tone from leadership and middle management, embedded compliance champions in business units, regular communication about why compliance matters. No tool enforces this. This is organisational design.</li></ol><p>Most compliance tooling addresses layer 1. Most audit failures happen in layers 2 and 3.</p><h3>What Policy-as-Code Cannot Touch</h3><p>Compliance teams routinely invest in automation and then express genuine surprise when they fail audits. The surprise is a symptom of conceptual confusion about what compliance frameworks measure. There is a category of compliance requirements that resists codification not in practice but in principle, and naming that category precisely matters.</p><h3>The codifiability spectrum</h3><p>Compliance requirements are not equally amenable to automated verification. They sit on a spectrum.</p><p>At the fully codifiable end: “all S3 buckets must have server-side encryption enabled.” A binary proposition about a configuration attribute. A rule engine checks it in milliseconds. No human judgment required.</p><p>Moving along: “access to production systems must be reviewed quarterly.” A process requirement. Execution is human, but the output (a signed record of the review) is a structured artifact that can be collected and verified automatically. IBM’s Auditree framework does exactly this — evidence collection modelled as unit tests, stored and versioned in git. Automatable at the evidence collection layer, even though the underlying process is human.</p><p>Further along: “personal data processing must have a documented lawful basis.” This is a legal judgment. A developer cannot make it by checking a flag in a database schema. It requires understanding the legal purpose of the processing, the relevant jurisdiction, and the applicable basis under GDPR Article 6. A tool can remind you to document it. A tool can check that the field is populated. A tool cannot determine whether the documented basis is legally correct.</p><p>At the fully uncodifiable end: “employees must maintain a culture of data protection by design.” A cultural norm. Real — organisations that embody it consistently make better privacy decisions than those that treat GDPR as a checklist. But no policy engine measures it, enforces it, or verifies it. It manifests in thousands of small decisions made by individuals who may never interact with a compliance system.</p><h3>Three categories that resist codification</h3><p><strong>Judgment calls about purpose and proportionality.</strong> GDPR’s data minimisation principle (Article 5(1)) requires that data be “adequate, relevant and limited to what is necessary in relation to the purposes for which they are processed” [13]. The word “necessary” carries enormous weight, and evaluating it requires a human in context.</p><p>A chatbot application collecting user interaction logs for product improvement: what log fields are necessary? Full conversation transcripts? Session IDs? Timestamps? Error events only? The answer depends on what “product improvement” means in your organisation, what less invasive alternatives exist, and a proportionality judgment that a legal or privacy professional has to make. Checkov cannot make this call. OPA cannot make this call. A compliance officer who understands the product can.</p><p>This category appears throughout the EU AI Act. Article 9 [15] requires providers of high-risk AI systems to implement risk management systems that identify and analyse “known and reasonably foreseeable risks.” The phrase “reasonably foreseeable” is explicitly a human judgment standard — a legal concept from tort law, not a configuration flag.</p><p><strong>Behaviour and culture controls.</strong> EU AI Act Article 4 [14] requires “AI literacy” across organisations deploying AI systems, in effect since February 2025. The regulation defines AI literacy as: “skills, knowledge and understanding that allow providers, deployers and affected persons, in a view commensurate with their roles, powers, and the tasks they are given, to deploy AI systems with awareness of opportunities and risks.”</p><p>This is a human development requirement. You cannot satisfy it by deploying a training module and ticking the completion box. An employee who clicks through compliance training without absorbing it is not AI-literate. Whether employees actually are AI-literate requires qualitative assessment — conversations, observed behaviour, decision-making quality — none of which reduces to a machine check.</p><p>The “tone from the middle” problem is similar. LRN’s research [11] shows that direct managers have more influence on employee compliance behaviour than formal policies or leadership communications. A manager who treats compliance as a bureaucratic imposition produces a team that treats compliance as a bureaucratic imposition, regardless of what the policy documentation says. Quantifying or automating management behaviour is not a tractable problem.</p><p><strong>Vendor and third-party relationships.</strong> GDPR Article 28 [16] requires written contracts with all data processors, specifying how personal data is processed. Article 28(3) sets out a detailed list of clauses that must be included. Compliance with Article 28 is technically documentable — you can maintain a register of DPAs and check whether each required clause is present.</p><p>Whether the vendor is actually complying with the terms of that DPA in practice is a different question. SOC 2 auditors consistently flag vendor management as a failure point — not because DPAs do not exist, but because organisations sign DPAs and then never monitor whether vendors honour them. This monitoring requires periodic assessments, audit rights exercised, and sometimes difficult conversations with commercial relationships. No tool automates the will to do this.</p><h3>The organisational design problem</h3><p>What these uncodifiable requirements have in common is that they describe properties of organisations — their culture, their governance, their relational practices — rather than properties of systems. Policy-as-code tools were built to reason about systems. They were not built to reason about organisations.</p><p>This is not a limitation that better tools will eventually overcome. It reflects a distinction between two types of compliance objects:</p><ul><li><strong>Technical systems</strong>: deterministic, observable, configurable, automatable.</li><li><strong>Organisations</strong>: probabilistic, partially observable, path-dependent, culturally constituted.</li></ul><p>A compliance program that treats the first as the only interesting problem will pass CI pipelines and fail audits. A program that understands both will design appropriately for each — automation where automation applies, human process and governance where it does not.</p><h3>Implications for AI systems specifically</h3><p>The compliance challenge is more acute for AI systems than for traditional IT systems. The EU AI Act’s risk-based approach means that controls applying to high-risk AI systems (Annex III categories: biometric identification, critical infrastructure, educational AI, employment AI) include requirements that are deeply contextual and judgment-dependent. The fundamental rights impact assessment under Article 27 [17] requires evaluating likely effects on individuals’ rights to non-discrimination, data protection, dignity, and effective remedy. These are not technical assessments.</p><p>The most powerful AI systems — including the LLMs that form the backend of most enterprise AI applications — are precisely the systems hardest to audit technically. You can check whether a model’s output contains certain prohibited categories. You cannot reliably determine whether the model’s decision-making for a consequential decision (a credit application, a CV screening, a medical diagnosis support) is free from problematic bias. Regulators know this. The AI Act’s conformity assessment requirements for high-risk systems are deliberately open-ended about technical methods because the field is not mature enough for prescriptive rules.</p><h3>What good looks like</h3><p>A mature compliance program for a high-risk AI application running under GDPR and the EU AI Act needs:</p><ol><li>Automated technical controls with machine-verifiable evidence (encryption, access controls, data retention enforcement, model input/output logging).</li><li>Structured human process for the controls that cannot be automated (lawful basis documentation, DPIA, risk management system, fundamental rights impact assessment, AI literacy programs, vendor management).</li><li>Governance structures that create accountability for cultural and behavioural dimensions (DPO with real authority, compliance embedded in product development, regular review cycles with leadership).</li><li>Audit readiness infrastructure that collects, organises, and signs evidence from all three layers in a format auditors can consume.</li></ol><p>OSCAL is a reasonable format for representing controls across all four layers — it has distinct models for catalogs, profiles, system security plans, assessment plans, and assessment results. Layer 1 controls can be assessed automatically. Layer 2 controls can be represented as manual attestations in the assessment-results model. Layers 3 and 4 require organisational commitment that no standard can mandate.</p><p>The practical limitation: building OSCAL tooling for layer 1 is the easy part. The hard part is designing the layer 2 process infrastructure — the scheduled reviews, the human attestation workflows, the escalation paths — so that people actually use it. That is a product design and organisational behaviour problem, not a standards problem.</p><h3>A Working Example That Takes Its Own Limitations Seriously</h3><p>The architecture I want to describe now is one I find genuinely useful, and I did not want to introduce it in a promotional register. The criticisms above came first because they are the lens through which any honest assessment of a compliance tooling project has to be made.</p><p><a href="https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot">compliance-ops-bedrock</a> [19] is a reference architecture for a compliance-aware agentic chatbot built on AWS Bedrock. It covers GDPR and EU AI Act obligations with a layer of OSCAL-based controls, automated evidence collection, and structured human process artifacts. It is in a public repository. It is also, to my knowledge, the most honest piece of compliance tooling I have encountered in the past year — honest in a specific sense: it documents its own gaps, builds audit-ready human process artifacts alongside automated ones, and the README explicitly enumerates what it does not cover. The repository itself has the implementation walkthrough; this section is about what the architecture demonstrates and what it doesn’t.</p><h3>The OSCAL gap that nobody has filled</h3><p>OSCAL is gaining serious traction, but there is a gap the tooling ecosystem has not addressed: there are no official OSCAL catalogs for GDPR or the EU AI Act. NIST has published OSCAL catalogs for SP 800–53 and SP 800–171. FedRAMP’s control baselines are available in OSCAL. For the two regulatory frameworks most relevant to European organisations and to anyone building AI applications used in Europe, the OSCAL ecosystem is empty. If you want to represent GDPR controls in OSCAL today, you write the catalog yourself.</p><p><a href="https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot">compliance-ops-bedrock </a>does this. The repository includes two hand-authored OSCAL catalogs: gdpr-minimal.yaml, covering 12 controls across Articles 5, 13, 17, 25, 28, 30, 32, 33, and 35; and eu-ai-act-minimal.yaml, covering 8 controls for a limited-risk GPAI chatbot (Articles 4, 50, 52, and Annex XI, adapted). Both catalogs are in OSCAL 1.1.2 format and pass trestle validation. The CI pipeline validates them on every push.</p><p>The README is honest about the status of these catalogs in a way worth quoting: “No official OSCAL catalogs for GDPR or the EU AI Act have been published by a standards body. Both catalogs in this repository were created for this project, based on the authors’ own reading and mapping of the regulations. The control coverage and mapping choices reflect editorial judgments, not a standardised or authoritative interpretation.”</p><p>That framing is appropriate. The catalogs are a starting point, not an authoritative mapping. They are the only publicly available starting point in OSCAL format for these regulations that I have found. Teams forking this repository will still need a privacy lawyer to review the control definitions before using them in a production compliance program — the mapping from regulatory text to control IDs requires legal judgment, not just technical work. What the catalogs provide is a structured skeleton and a format that integrates with the rest of the OSCAL toolchain.</p><h3>Where the architecture sits on the codifiability spectrum</h3><p>The architecture maps onto the codifiability spectrum explicitly, and understanding where it sits is more useful than a feature list.</p><p><strong>Fully automated, machine-verifiable evidence.</strong> A boto3-based evidence collection script queries CloudTrail status, IAM password policy settings, S3 bucket configurations, GuardDuty detector status, and the list of available Bedrock models. Artifacts land in evidence/automated/ as JSON files. They are deterministic snapshots of actual infrastructure state. When the compliance report is generated, these files are read directly — no manual curation, no LLM inference about what they mean. This is exactly the layer where automation is appropriate.</p><p>The CI pipeline sits here too: mypy type checking, YAML schema validation, OSCAL trestle validation, and a report dry-run, on AWS CodeBuild. Two terraform projects (plan on PR, apply manually) and a separate CI project running the full validation suite on every push. Straightforward quality gates that catch structural problems before they reach a reviewer.</p><p><strong>Structured-but-human.</strong> This is the more interesting part, and it is where the architecture makes its most distinctive contribution.</p><p>Consider how the attestation system works. Each of the 20 controls in the two catalogs has a corresponding attestation in attestations/initial-attestations.yaml. Each attestation has a status field (satisfied, partial, not-satisfied, or not-applicable), a decision field (a one-sentence conclusion), a justification field (a multi-paragraph prose explanation), a reviewed-by field, and optional evidence-refs that link the attestation to specific files or URLs. The schema is enforced.</p><p>What this produces is not a pass/fail compliance dashboard. It is a structured record of human judgment. The attestation for gdpr-5-1-a (lawfulness, fairness, and transparency) shows: status partial, because the system currently processes only synthetic data, a full Legitimate Interest Assessment has not been completed, and a privacy notice does not yet exist. That is an honest statement of where things stand. The attestation for gdpr-30 (ROPA): status satisfied, with references to ropa-entry.yaml and an explicit note that legal entity fields must be completed before production. These are the kinds of nuanced assessments that produce useful compliance documentation — not the green-dashboard theatre that produces audit failures.</p><p>The human procedure documents follow the same logic. IRP-001 is a full incident response procedure covering the 72-hour GDPR Art. 33 notification clock, with detection channels (GuardDuty, CloudTrail, S3 access logs), severity classification, containment steps with actual AWS CLI commands, and a notification timeline table broken into six phases from detection to post-72-hour reporting. ROPA-001 is a complete Art. 30 record with all mandatory fields populated, the ones requiring a legal entity identity clearly marked [TBD], and a DPIA assessment that defers to pre-production review. HOP-001, the human oversight procedure, specifies who monitors the system, how often, what they are looking for, what their override authority is, and includes an AI literacy record signed by the operating engineer.</p><p>These are not boilerplate templates. They are documents that could be handed to a GDPR auditor with the expectation the auditor would find them useful rather than embarrassing.</p><p><strong>Explicitly out of scope.</strong> The README’s “What this repository does not include” section lists: adversarial attack evaluation or red-teaming, dynamic application security testing, organisation-wide compliance posture assessment, AI-based inference about infrastructure compliance, AI-written compliance narrative, and landing zone or enterprise centralised cloud controls. These exclusions are not failures of ambition — they are accurate scope boundaries. A reference architecture trying to cover all of these would be either dishonest or unusable.</p><h3>What this means for the three-layer model</h3><p>The three-layer model from the previous section maps onto <a href="https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot">compliance-ops-bedrock</a> cleanly.</p><p><strong>Layer 1 (technical controls, automated).</strong> Well covered. Encryption at rest using a customer-managed KMS key. TLS enforcement via Lambda Function URL settings. IAM least-privilege roles, verifiable through the Terraform files and the automated IAM evidence collection. GuardDuty active with EventBridge-to-SNS alerting for MEDIUM and above findings. CloudTrail with 90-day retention. S3 public access block on all application buckets. A dedicated report bucket — publicly readable by design, using default SSE-S3, hosting the static HTML compliance report as a website — with no personal data or secrets. These controls are deployed, the evidence is collected automatically, and the attestations reference specific evidence files. A reviewer can trace from control to attestation to evidence in a few minutes.</p><p>The EU AI Act Art. 50 transparency implementation deserves particular mention because it is one of the few places I have seen this obligation implemented at the API layer rather than described in documentation. Every response from the Lambda includes an X-AI-Generated: true HTTP header, an X-AI-System: compliance-ops-bedrock-demo header, and an ai_disclosure field in the JSON body that explicitly states the response is AI-generated and not legal advice. The system prompt instructs the model to identify itself as an AI system if asked. Not a documentation commitment about future behaviour. The actual behaviour, verifiable from the code.</p><p>The Art. 50 obligations become fully enforceable in August 2026. Neither the Commission nor any national supervisory authority has published guidance on what “prominent notice” means for an API-only system that has no consumer UI. The second draft Code of Practice on AI-generated content, published March 2026, is oriented toward media and consumer-facing products. The HTTP-headers-plus-JSON-disclosure approach is a reasonable interpretation of what technical disclosure looks like for a B2B API chatbot, but it has not been validated against any supervisory authority’s stated standard, because no such standard yet exists.</p><p><strong>Layer 2 (operational process controls, structured manual evidence).</strong> This is where the architecture is unusual among open-source compliance tooling. The four human procedure documents — IRP-001, ROPA-001, the DPA breach notification template, and HOP-001 — are first-class structured artifacts in the repository, version-controlled alongside the code and infrastructure. They are cross-referenced in attestations.</p><p>The DPA notification template covers all Art. 33(3) mandatory fields with FILL/ASSESS annotations for completion at incident time. This is practical audit readiness. When an auditor asks “show me your Art. 33 notification process,” the answer is not a description of a process that exists somewhere — it is a structured template with every required field pre-mapped and evidence references pointing to IRP-001.</p><p>The attestation review mechanism is an honest attempt at layer 2 process. Each attestation carries reviewed-by and reviewed-at fields. Whether that review cadence is actually maintained over time depends entirely on the team operating the system — the repository provides the structure, not the organisational will to use it. A compliance program that uses this repository but treats the attestations as a one-time setup will gradually drift out of compliance without the repository noticing.</p><p><strong>Layer 3 (cultural and governance controls).</strong> Not here, and the architecture does not pretend otherwise. HOP-001 includes a table of system limitations requiring human judgment — hallucination risk, knowledge cutoff, scope boundaries, jurisdictional variation. That table is accurate and useful. But a markdown table does not create a culture of data protection by design. It does not make managers take privacy seriously in product decisions. It does not ensure the compliance review process is maintained when the team is under delivery pressure. Layer 3 cannot be in a repository.</p><h3>The report as a design choice</h3><p>The compliance report generated is worth discussing as a design decision. It is a static HTML file, generated deterministically from the OSCAL catalogs, attestations, and evidence JSON files by a Jinja2 template. It contains no LLM-written content. It displays attestation statuses, prose justifications, evidence references, and gap flags. It is designed to be published to the dedicated report S3 bucket — a public static website — and shown to auditors.</p><p>This design choice reflects a specific concern: compliance tooling has a trust problem when it uses AI to generate compliance narratives. A compliance report written in whole or in part by an LLM is a document an auditor cannot verify — the model may have presented partial coverage as complete, may have generated plausible-sounding justifications that do not reflect actual control implementation, may have smoothed over gaps that should be visible. The static HTML report avoids this entirely by being nothing more than a structured display of what humans wrote and what automated scripts collected. Every statement in it can be verified by reading the source files.</p><p>The report’s own disclaimer — “This is a prototype report” — is honest. A production version would need independent review of the attestations, not just self-assessment. The attestation schema supports reviewed-by fields precisely because the intent is that attestations should be reviewed by someone other than the person who wrote them. For a single-engineer prototype, that separation is not currently achievable. For a production deployment, it is a prerequisite.</p><h3>What a team forking this would still need to do</h3><p>Eliding the gap between a reference architecture and a production compliance program is how compliance theatre gets built. A team forking <a href="https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot">compliance-ops-bedrock</a> for a real production deployment would need, at minimum:</p><p><strong>Legal review of the OSCAL catalogs.</strong> The control definitions are the authors’ own reading of GDPR and the EU AI Act. They are a reasonable starting point. They have not been reviewed by a privacy lawyer or a regulatory specialist. Before these catalogs form the basis of a compliance program, someone with legal expertise needs to validate the control-to-article mappings, identify coverage gaps, and assess whether the attestation criteria are sufficient under the regulatory standards that apply.</p><p><strong>Completion of the partial and not-satisfied attestations.</strong> Eight of the twenty attestations are partial or not-satisfied. These represent real compliance gaps: the Legitimate Interest Assessment for lawful basis, the privacy notice, the right-to-erasure procedure, the pseudonymisation assessment. For a production system processing real personal data, these are not deferred items. They are prerequisites.</p><p><strong>A DPIA before production launch.</strong> The attestation for gdpr-35 (DPIA) is marked not-applicable for the demo phase, correctly, because the demo processes only synthetic data. Any production deployment processing real user data at scale with LLM inference needs a DPIA. The architecture does not produce that document — it flags that the document needs to exist.</p><p><strong>A DPO appointment decision.</strong> The ROPA marks the DPO field as TBD. Whether a DPO is required depends on the scale of processing and the organisational context. A legal determination, not a technical one.</p><p><strong>An actual access review schedule.</strong> Several attestations note that the absence of a formal access review schedule is acceptable for a single-operator prototype but not for a production system. A production deployment needs periodic access reviews with signed records, not just a note that they should happen.</p><p><strong>Bedrock Guardrails configuration.</strong> The attestation for euaia-deployer-1 (human oversight) explicitly identifies Bedrock Guardrails as a known gap before any public deployment. The architecture demonstrates where guardrails would be configured; it does not configure them, because the demo scope does not require them. A production deployment serving external users needs guardrails for harmful content blocking before launch, not after the first incident. The planned AgentCore migration is the cleaner path to closing this gap, but it has not landed yet.</p><p>None of these gaps are hidden. The attestations themselves flag them. The architecture is designed to surface what is incomplete rather than paper over it. A team that reads “partial” in an attestation and ships to production anyway has used the tooling as theatre rather than as compliance infrastructure.</p><h3>Why this matters now</h3><p>The EU AI Act’s full high-risk AI system requirements apply from August 2026. The limited-risk transparency obligations under Art. 50 are already in force, though enforceable at national level only once member states have designated competent authorities — a process that, as of April 2026, Germany has still not completed (a draft bill, KI-MIG, passed cabinet in February 2026 and awaits Bundestag passage). FedRAMP’s OSCAL mandate arrives in September 2026. The window in which teams can plan compliance architectures before these obligations become enforceable is closing.</p><p>Most teams are not starting from a mature OSCAL-based compliance infrastructure. Most are starting from spreadsheets, or from ad hoc documentation scattered across wikis and Confluence, or from compliance platforms that provide checklists but not structured evidence. The jump from any of those starting points to a working OSCAL-based system with automated evidence collection, structured attestations, and audit-ready human procedure documents is not small.</p><p>A reference architecture that covers GDPR and EU AI Act controls in OSCAL format, with real implementation examples and honest gap documentation, is useful precisely because it is concrete. Abstract descriptions of what compliance should look like are easy to find. Working code that demonstrates how to structure a ROPA as a version-controlled YAML file, how to implement Art. 50 transparency disclosure at the API layer, and how to generate a deterministic compliance report from structured artifacts — that is harder to find. Full implementation details, the attestation files themselves, and the evidence collection scripts are in the <a href="https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot">project’s GitHub page</a> [19].</p><p>The architecture does not make compliance easy. Nothing makes compliance with GDPR and the EU AI Act easy. It makes the hard parts more tractable, and it is honest about which parts it cannot address. That combination is rarer than it should be.</p><h3>References</h3><p>[1] Wiz, “Compliance as Code: A Complete Guide.” <a href="https://www.wiz.io/academy/compliance/compliance-as-code">https://www.wiz.io/academy/compliance/compliance-as-code</a></p><p>[2] Drata, “Challenges in Shift-Left Compliance and How to Address Them.” <a href="https://drata.com/blog/challenges-in-shift-left-compliance-and-how-to-address-them">https://drata.com/blog/challenges-in-shift-left-compliance-and-how-to-address-them</a></p><p>[3] Linford &amp; Company, “SOC Audit Failure: Common Mistakes.” <a href="https://linfordco.com/blog/soc-audit-failure-common-mistakes/">https://linfordco.com/blog/soc-audit-failure-common-mistakes/</a></p><p>[4] Permit.io, “Everyone Loves Policy as Code, No One Wants to Write Rego.” <a href="https://www.permit.io/blog/no-one-wants-to-write-rego">https://www.permit.io/blog/no-one-wants-to-write-rego</a></p><p>[5] Trend Micro, “Policy as Code vs Compliance as Code.” <a href="https://www.trendmicro.com/en_us/research/23/c/policy-as-code-vs-compliance-as-code.html">https://www.trendmicro.com/en_us/research/23/c/policy-as-code-vs-compliance-as-code.html</a></p><p>[6] Spacelift, “Policy as Code Tools.” <a href="https://spacelift.io/blog/policy-as-code-tools">https://spacelift.io/blog/policy-as-code-tools</a></p><p>[7] OSCAL Foundation. <a href="https://oscalfoundation.org/">https://oscalfoundation.org/</a></p><p>[8] IAPP, “What role can internal auditors play in GDPR compliance?” <a href="https://iapp.org/news/a/what-role-can-internal-auditors-play-in-gdpr-compliance">https://iapp.org/news/a/what-role-can-internal-auditors-play-in-gdpr-compliance</a></p><p>[9] ComplyDog, “GDPR Audit: Complete Compliance Audit Guide 2025.” <a href="https://complydog.com/blog/gdpr-audit-complete-compliance-audit-guide-2025">https://complydog.com/blog/gdpr-audit-complete-compliance-audit-guide-2025</a></p><p>[10] Centraleyes, “What Happens If I Fail a SOC 2 Audit?” <a href="https://www.centraleyes.com/soc-2/what-happens-if-i-fail-a-soc-2-audit/">https://www.centraleyes.com/soc-2/what-happens-if-i-fail-a-soc-2-audit/</a></p><p>[11] LRN, “2025 Ethics and Compliance Program Maturity Report” (via Corporate Compliance Insights). <a href="https://www.corporatecomplianceinsights.com/lrn-2025-program-maturity-report/">https://www.corporatecomplianceinsights.com/lrn-2025-program-maturity-report/</a></p><p>[12] Dragnet Secure, “Regulatory Compliance and Human Error: Navigating the Human Factor in 2025’s Evolving Cybersecurity Landscape.” <a href="https://www.dragnetsecure.com/blog/regulatory-compliance-human-error-navigating-the-human-factor-in-2025s-evolving-cybersecurity-landscape">https://www.dragnetsecure.com/blog/regulatory-compliance-human-error-navigating-the-human-factor-in-2025s-evolving-cybersecurity-landscape</a></p><p>[13] GDPR Article 5 — Principles relating to processing of personal data. <a href="https://gdpr-info.eu/art-5-gdpr/">https://gdpr-info.eu/art-5-gdpr/</a></p><p>[14] EU AI Act Article 4 — AI literacy. <a href="https://artificialintelligenceact.eu/article/4/">https://artificialintelligenceact.eu/article/4/</a></p><p>[15] EU AI Act Article 9 — Risk management system. <a href="https://artificialintelligenceact.eu/article/9/">https://artificialintelligenceact.eu/article/9/</a></p><p>[16] GDPR Article 28 — Processor. <a href="https://gdpr-info.eu/art-28-gdpr/">https://gdpr-info.eu/art-28-gdpr/</a></p><p>[17] EU AI Act Article 27 — Fundamental rights impact assessment. <a href="https://artificialintelligenceact.eu/article/27/">https://artificialintelligenceact.eu/article/27/</a></p><p>[18] NIST OSCAL Models. <a href="https://pages.nist.gov/OSCAL/about/">https://pages.nist.gov/OSCAL/about/</a></p><p>[19] compliance-ops-bedrock — Reference Architecture (GitHub). <a href="https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot">https://github.com/LeonardoSanBenitez/ComplianceOps-Reference-Architecture-for-Bedrock-Agentic-Chatbot</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38345bd8b780" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Testing Techniques for Machine-Learning-Intensive Softwares]]></title>
            <link>https://medium.com/@lsbenitezpereira/automated-testing-techniques-for-machine-learning-intensive-softwares-7978591630a5?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7978591630a5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 02:59:01 GMT</pubDate>
            <atom:updated>2023-01-15T02:59:01.089Z</atom:updated>
            <content:encoded><![CDATA[<p>This text was mostly <strong>generated automatically</strong> using the tool <strong>ChatGPT</strong>, and it is meant only for research purposes. I’ve used it to write the bulk of the text, while I took care of organizing the text, proofreading, guaranteeing technical correctness, and defining the topics.</p><p>All technical information was checked, but I may have missed some details. I carefully verified if the generated text was already published somewhere, but please let me know If you find any copyright infringement and I’ll correct it immediately.</p><p>Past publications in this series of ChatGPT-written articles:</p><ul><li><a href="https://medium.com/@lsbenitezpereira/three-devops-practices-to-keep-you-data-science-team-sane-9e866a948b95">Three DevOps practices to keep you data science team SANE</a></li><li><a href="https://medium.com/@lsbenitezpereira/running-inference-of-machine-learning-models-on-the-cloud-767e4b82cb28">Running Inference of Machine Learning Models on the Cloud</a></li></ul><h3>Introduction</h3><p>Automated testing is an essential component of the modern software development process, and machine learning (ML) intensive applications are no different. These types of software are complex and require a <strong>thorough testing approach</strong> to ensure their functionality and accuracy. In this article, we will explore some of the most effective automated testing techniques for ML-intensive systems and how you can include it all in your routine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4zk1wseDlz3lyTOVvZEEQ.jpeg" /><figcaption>Image source: Brian Wangenheim</figcaption></figure><h3>Types of testing</h3><p>Different types of testing serve different purposes and are used at <strong>different parts of the development process</strong>. Each category of test provides a different level of assurance for the quality of the system, and by using a combination of them, you can guarantee that your software is working properly, efficiently and is meeting the user’s requirements.</p><p><strong>Unit testing</strong> is a technique that involves testing individual units or components of the software. This approach is useful for testing the correctness of the code and ensuring that each small block of the software is functioning as intended. In the context of ML-intensive software, unit testing can be used to test the functionality of the ML models and the accuracy of their predictions.</p><p><strong>Integration testing</strong> is a technique that tests the interactions between different components of the software. This method is useful for testing how the different parts of the software work together and identifying any integration issues. In the context of ML-intensive software, integration testing can be used to test the interactions between the ML models and other components of the software, such as the user interface.</p><p><strong>Functional testing</strong> is an approach that tests the software’s functionality against its requirements. This approach is useful for ensuring that the software is meeting its intended purpose and that it is working as expected. In the context of ML-intensive software, functional testing can be used to test the models’ ability to perform the tasks they were designed to perform.</p><p><strong>Performance testing</strong> is a technique that tests the software’s performance under a variety of conditions. This approach is useful for identifying bottlenecks and optimizing the software’s performance. In the context of ML-intensive software, performance testing can be used to test the efficiency of the ML models and their ability to handle large amounts of data.</p><p><strong>Regression testing</strong> is a technique that tests the software’s functionality after changes have been made. This approach is useful for ensuring that changes to the software have not introduced any new bugs or issues. In the context of ML-intensive software, regression testing can be used to test the accuracy of the ML models after changes have been made to the code or the data.</p><h3>Popular Libraries</h3><p>Many testing libraries are popular among the machine learning community. As <strong>Python</strong> is the most popular language in the field, I’ll restrain this section to only python libraries.</p><p><strong>Pytest</strong> is a popular library for automated testing that provides several helpful features, such as test discovery, test parameterization, and test reporting. Here is an example of how to use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/712579fab437a3df26fd06370f5b277e/href">https://medium.com/media/712579fab437a3df26fd06370f5b277e/href</a></iframe><p><strong>Hypothesis</strong> is a library for property-based testing. It generates randomized test inputs to check the properties of your code. Here, test_my_function is decorated with the given decorator from Hypothesis, it will generate randomized lists of integers and use them as input for the test, then the test asserts that the output of the function is equal to the length of the input list:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e35a7bb28e408891b21a9915808ad07/href">https://medium.com/media/8e35a7bb28e408891b21a9915808ad07/href</a></iframe><h3>Including automated tests in your routine</h3><p>As a data scientist, incorporating automated testing into your daily routine can be a bit different than traditional software development. Here are a few tips on how to acquire the mindset of writing automated tests:</p><ol><li><strong>Start small</strong>: Automated testing can be overwhelming at first, so start small. Write tests for simple functions or small parts of your code, and gradually build up to more complex tests.</li><li><strong>Test early, test often</strong>: The earlier you start testing, the easier it is to identify and fix issues. Make testing a part of your development process and run tests often to catch issues early on.</li><li><strong>Focus on the important parts</strong>: Not all parts of your code need to be tested. Focus on the parts that are important for your project and that you expect to change frequently.</li><li><strong>Use testing frameworks</strong>: There are several testing frameworks available, such as pytest or unittest. These frameworks make it easy to write and run automated tests, and they supply a lot of useful features.</li><li><strong>Write testable code</strong>: Writing testable code can be challenging, but it’s essential for automated testing. Make sure your code is modular, and that it follows good software development practices.</li><li><strong>Test the whole pipeline</strong>: Automated testing is not limited to testing functions, it’s also important to test the whole pipeline including data loading, preprocessing, training, and inference stages.</li></ol><p>By following these tips, you can gradually acquire the mindset of writing automated tests and make it a <strong>habit</strong>. This habit will help you to build more robust and reliable machine learning systems, which will make your work more efficient and easier to maintain.</p><h3>Conclusion</h3><p>Automated testing is an essential part of developing ML-intensive software, because it helps to e<strong>nsure that the code is working</strong> and that the <strong>ML models are performing as intended</strong>. Various types of tests can be used for ML-intensive software, such as unit testing or integration testing, and you should keep in mind the differences when writing your tests. Various Python libraries can be used to automate these tests, such as pytest or Hypothesis, and you should check which of them better adapt to your use case.</p><p>By following these practices, you can build more <strong>robust and reliable ML systems</strong>, which will make your work more efficient and easier to maintain. Automated testing can be a powerful tool for data scientists to improve the quality of their models, increase confidence in their results, and make the development process more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7978591630a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three DevOps practices to keep you data science team SANE]]></title>
            <link>https://medium.com/@lsbenitezpereira/three-devops-practices-to-keep-you-data-science-team-sane-9e866a948b95?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e866a948b95</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 03:21:38 GMT</pubDate>
            <atom:updated>2023-01-02T03:21:38.127Z</atom:updated>
            <content:encoded><![CDATA[<p>This text was mostly <strong>generated automatically</strong> using the tool <strong>ChatGPT</strong>, and it is meant only for research purposes. I’ve used it to write the bulk of the text, while I took care of organizing the text, proofreading, guaranteeing technical correctness, and defining the topics.</p><p>All technical information was checked, but I may have missed some details. I carefully verified if the generated text was already published somewhere, but please let me know If you find any copyright infringement and I’ll correct it immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vozpVBcbW4KYaoZe_RVtdQ.jpeg" /><figcaption>Photo Source: <a href="https://unsplash.com/@eldarnazarov">Eldar Nazarov</a></figcaption></figure><h3>Introduction</h3><p>As a data scientist, you are constantly faced with challenges that can drive you <strong>insane</strong>. You have to deal with messy and incomplete data, wrangle with complex algorithms, and navigate the often-fraught process of getting your models into production. To summarize the <strong>characteristic of highly productive data science teams</strong>, I created the acronym SANE:</p><ul><li><strong>Sustainable</strong>: use tools and practices that are easy to maintain and can remain in use over the long term.</li><li><strong>Automated</strong>: adopt DevOps practices to automate the testing and deployment of their models, freeing them up to focus on more complex tasks.</li><li><strong>Nimble</strong>: adapt to changing circumstances and pivot their approach as needed, by using agile development methodologies and flexible tools and processes.</li><li><strong>Efficient</strong>: achieve a desired result with minimal waste, by streamlining workflows and using the most appropriate tools for the task at hand.</li></ul><p>Sounds great, right? Here are some DevOps practices that can make your life as a data scientist more SANE.</p><h3>Version control</h3><p>In software development, version control is a system that <strong>tracks changes</strong> to code and documents over time, allowing developers to <strong>review and revert </strong>changes as needed. In data science, version control is also an important tool for tracking changes to <strong>data, models, and other artifacts</strong>.</p><p>There are a number of available version control systems for code, where <strong>Git</strong> is the most widely used. However, Git is not well suited for large files, which is usually the case with datasets and machine learning models. There are a number of tools that can help with this, such as:</p><ul><li><strong>DVC</strong>: DVC is an open-source version control system specifically designed for data and machine learning models. It allows data scientists to track changes to their data and models, and to reproduce past results or compare different versions.</li><li><strong>Pachyderm</strong>: Pachyderm is another open-source version control system for data and machine learning models. It provides features such as reproducibility, collaboration, and data lineage, making it a powerful tool for data science workflows.</li><li><strong>Quilt</strong>: Quilt is a cloud-based version control system for data. It allows data scientists to track changes to their data and collaborate with their team, and provides features such as data discovery and data lineage.</li></ul><p>Overall, version control is an important tool for data science teams, helping them track and manage changes to their code, data, and models, and collaborate more effectively with their team.</p><h3>Automated testing</h3><p>Automated testing is the practice of <strong>using software to run tests</strong> on code, data, and other artifacts to ensure that they are correct and meet the desired quality standards. In data science, automated testing is an important tool for <strong>ensuring the accuracy and reliability</strong> of machine learning models and other data-driven systems.</p><p>There are a number of peculiarities of data science that make automated testing particularly important. One of the main <strong>challenges</strong> is that data science workflows often involve <strong>complex and dynamic data</strong>, which can be difficult to test and validate. Automated testing can help data scientists ensure that their models are robust and accurate, even when faced with changing or unexpected data.</p><p>Another challenge in data science is the need to <strong>ensure reproducibility and collaboration</strong>. Automated testing can help data scientists ensure that their code and models are consistent and reliable, and that they can be easily reproduced by others.</p><p>There are a number of tools and techniques that data scientists can use to automate testing in their workflows. Some common approaches include unit testing, integration testing, and end-to-end testing. Data scientists can also use practices such as continuous integration and delivery (CI/CD) to automate the executions of the tests, making it easier to test and release new models and updates.</p><p>Overall, automated testing is an important tool for data science teams, helping them ensure the accuracy and reliability of their models and other code and data-driven systems, and enabling reproducibility and collaboration.</p><h3>Infrastructure as Code (IaC)</h3><p>Infrastructure as Code is a practice that involves <strong>using code and automation to define, manage, and deploy infrastructure</strong> for applications and systems. The goal of IaC is to make it easier to provision, configure, and manage infrastructure, and to enable more agile and efficient development and deployment processes.</p><p>In IaC, infrastructure is defined using code, typically in a high-level language such as Python, Ruby, or YAML. This code is stored in version control and can be <strong>reviewed, tested, and versioned</strong> just like any other codebase. When it comes time to deploy or update infrastructure, the code is executed, provisioning and configuring the necessary resources automatically.</p><p>There are a number of benefits to using IaC in data science workflows. It can help data scientists automate and streamline their infrastructure management, reducing the time and effort required to set up and maintain their environments. It also makes it easier to version and track changes to infrastructure, which is important for ensuring reproducibility and collaboration. Finally, IaC can help data scientists more easily scale and adapt their infrastructure as their needs change, making it easier to respond to new challenges and opportunities.</p><p>Overall, IaC is a powerful tool for data science teams, helping them automate and streamline their infrastructure management, improve reproducibility and collaboration, and scale and adapt more easily.</p><h3>Conclusion</h3><p>Implementing these DevOps practices can help your data science team staying SANE (Sustainable, Automated, Nimble and Efficient), allowing you to focus on what matters most: <strong>solving complex problems and driving business value</strong>. So, try to adopt these practices and see if the team is better equipped to tackle the complex and dynamic challenges of the modern data landscape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e866a948b95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Inference of Machine Learning Models on the Cloud]]></title>
            <link>https://medium.com/@lsbenitezpereira/running-inference-of-machine-learning-models-on-the-cloud-767e4b82cb28?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/767e4b82cb28</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 03:46:05 GMT</pubDate>
            <atom:updated>2023-01-02T03:24:04.662Z</atom:updated>
            <content:encoded><![CDATA[<p>This text was mostly <strong>generated automatically</strong> using the tool <strong>ChatGPT</strong>, and it is meant only for research purposes. All technical information was checked, but I may have missed some details. I carefully verified if the generated text was already published somewhere, but please let me know If you find any copyright infringement and I’ll correct it immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4QpdBM516FvHCha1B67-Yw.jpeg" /><figcaption>Image source: Alina Grubnyak</figcaption></figure><h3>Introduction</h3><p>Running inference of machine learning models on the cloud can be a cost-effective and scalable solution for <strong>deploying your models to production</strong>. In this tutorial, we will go over the steps involved in running inference of machine learning models on the cloud, including:</p><ol><li>Preparing the model for deployment</li><li>Setting up a cloud infrastructure</li><li>Running inference</li><li>Monitoring and scaling</li></ol><p><strong>Cloud-native machine learning services</strong> — such as Amazon SageMaker, GCP Cloud AI Platform, and Azure Machine Learning — are fully managed services that help you with these 4 steps. These services offer easy-to-use interfaces and typically handle the underlying infrastructure, allowing you to focus just on the machine learning tasks.</p><p>Overall, running inference of machine learning models on the cloud can be a powerful and flexible way to deploy your models to production. By following these steps and leveraging the resources provided by cloud providers, you can <strong>easily run inference at scale</strong> and serve your models to a wide audience.</p><h3>Preparing the model for deployment</h3><p>Preparing the model for deployment involves ensuring that the model is in a format that can be used for inference and packaging it up with any necessary dependencies. Some specific steps you may need to take in this process include:</p><ol><li><strong>Exporting the model:</strong> Depending on the training environment you used, you may need to export the trained model to a file or files that can be used for inference. For instance, if you trained the model using TensorFlow, you may need to use the tf.saved_model.save function to save the model to a file.</li><li><strong>Converting the model:</strong> If the model is not in a format that is supported by your inference environment, you may need to convert it to a suitable format. For example, you may need to convert a TensorFlow model to ONNX format if you plan to use the ONNX runtime for inference.</li><li><strong>Packaging the model and dependencies:</strong> Once the model is in a suitable format, you will need to package it up with any necessary dependencies, such as software libraries and frameworks. This may involve creating a ZIP file or Docker image that contains the model files and dependencies.</li></ol><p>It is important to note that the specific steps involved in preparing the model for deployment will depend on the training and inference environments you are using, as well as the format of the model and any dependencies it requires. Furthermore, cloud-native machine learning services can significantly ease the process of preparing the model for deployment, allowing you to focus on building and training your models. By using them, you can significantly reduce the time and effort involved in preparing the model for deployment, making it easier to get your models up and running in production.</p><h3>Setting up a cloud infrastructure</h3><p>Setting up a cloud infrastructure for running machine learning models on the cloud can involve <strong>either creating a custom infrastructure</strong> for computing and storage <strong>or using cloud-native machine learning services</strong>.</p><p>If you choose to use <strong>cloud-native machine learning services</strong>, you can skip many steps involved in creating a custom infrastructure. These services typically offer an easy-to-use interface for training and deploying machine learning models, as well as automatic scaling and resource management.</p><p>Using them can be a convenient and cost-effective way to set up a cloud infrastructure for running machine learning models, as it can save you the time and effort of setting up and configuring a custom infrastructure. However, these services may <strong>not offer as much flexibility and control</strong> as creating a custom infrastructure, so you will need to consider your specific needs and requirements when deciding which option to choose.</p><blockquote>“Using cloud-native machine learning services can be convenient and cost-effective”</blockquote><p>If you choose to create a <strong>custom infrastructure</strong>, you may want to set up a cloud infrastructure that includes one or more virtual machines (VMs) with GPUs, as well as a storage solution for your data and model files. Several cloud providers offer these services too, such as Amazon Web Services (AWS), Google Cloud Platform (GCP), and Microsoft Azure.</p><p>Once you have your custom infrastructure set up, you will need to <strong>install any necessary dependencies</strong> on your VMs. This may include software libraries and frameworks that are required to run your model, such as TensorFlow or PyTorch. The next step is to <strong>load the model into memory</strong> on your VMs. This may involve transferring the model files to the VMs over the network or using a cloud storage solution such as Amazon S3 or Google Cloud Storage.</p><h3>Running inference</h3><p>Running inference involves sending input data to the machine learning model and receiving predictions in return. There are several ways you can run inference on the cloud, including using an API or a command-line interface (CLI).</p><p>Here are <strong>some examples</strong> of how you can run inference using an API:</p><ul><li>Using the requests library in Python:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3471b279d3800efce781f0fd920c006/href">https://medium.com/media/f3471b279d3800efce781f0fd920c006/href</a></iframe><ul><li>Using the HTTPClient class in C#:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/147ad09caf3a61191b5fbe8b3f6ca348/href">https://medium.com/media/147ad09caf3a61191b5fbe8b3f6ca348/href</a></iframe><ul><li>Using the curl command in a terminal:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac3a998bf4ff8c86e7bfa7b92feafcfb/href">https://medium.com/media/ac3a998bf4ff8c86e7bfa7b92feafcfb/href</a></iframe><p>These are just a few examples of how you can run inference on the cloud. The specific steps you will need to take will depend on the type of model you are using and the environment in which it is running. It is important to note that you may need to authenticate your API calls or CLI commands in order to access the model and run inference.</p><h3>Monitoring and scaling</h3><p>Monitoring and scaling up are important considerations when running machine learning models on the cloud, as they can help ensure that your models are performing well and are able to handle the workload.</p><p>Here are some specific steps you may want to take to monitor and scale up your models on the cloud:</p><ol><li><strong>Monitor performance: </strong>You will want to monitor the performance of your models to ensure they are running smoothly and providing accurate predictions. You can use monitoring tools provided by your cloud provider, such as AWS CloudWatch or GCP Stackdriver, to track metrics such as CPU and memory usage, as well as custom metrics specific to your model.</li><li><strong>Monitor availability:</strong> In addition to monitoring performance, you will also want to monitor the availability of your models to ensure they are accessible to users. You can use tools such as health checks and uptime monitoring to track the availability of your models and receive alerts if they become unavailable.</li><li><strong>Scale up:</strong> If you need to handle a larger volume of inference requests, you may need to scale up your infrastructure by adding more VMs or GPUs. You can use autoscaling features provided by your cloud provider to automatically allocate additional resources as needed.</li><li><strong>Load balance:</strong> If you have multiple VMs or GPUs running your model, you may want to use a load balancer to distribute the workload evenly among them, ensuring that your model can handle the workload and provide fast and accurate predictions. Most cloud-native machine learning services already offer load balancing out-of-the-box.</li></ol><p>Overall, monitoring and scaling up your models on the cloud can help ensure that they are performing well and are capable of handling the workload. By leveraging the tools and services provided by cloud providers, you can easily monitor and scale your models as needed.</p><blockquote>“Monitoring and scaling ensures that your models are capable of handling the workload”</blockquote><p>The <strong>cloud offers several advantages over on-premises</strong> infrastructure that can make it easier to monitor and scale up your models. One advantage of the cloud is that it provides a highly scalable infrastructure that can automatically allocate additional resources as needed. This can be particularly useful when running machine learning models, as the workload can vary significantly depending on the volume of inference requests. Another advantage of the cloud is that it provides a range of tools and services for managing the infrastructure. This can include monitoring, logging, and error tracking, among others.</p><h3>Conclusion</h3><p>In this article, we learned about the steps involved in running the inference of machine learning models on the cloud. We discussed how to prepare the model for deployment, set up a cloud infrastructure, run inference, and scale as needed. We also highlighted the advantages of the cloud over on-premises infrastructure, including scalability and the availability of tools and services for making inferences with your models.</p><p>Overall, running inference of machine learning models on the cloud can be a convenient and cost-effective solution for deploying your models to production. By following the steps outlined in this article and leveraging the resources provided by cloud providers, you can easily run inference at scale and serve your models to a wide audience. <strong>By using the cloud, you can take advantage of the scalability and monitoring capabilities it offers</strong>, as well as the convenience of using cloud-native machine learning services, to ensure that your models are running smoothly and efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=767e4b82cb28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline IoT projects with Infrastructure as Code]]></title>
            <link>https://medium.com/@lsbenitezpereira/streamline-iot-projects-with-infrastructure-as-code-eb8921909c4c?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb8921909c4c</guid>
            <category><![CDATA[azure-iot-hub]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[jetson-nano]]></category>
            <category><![CDATA[azure-pipelines]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 02:33:46 GMT</pubDate>
            <atom:updated>2022-03-09T02:33:46.235Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is the second of a series about using containers for embedded systems, where in the <a href="https://medium.com/@lsbenitezpereira/containers-for-embedded-systems-7c5929bacf1e">first post</a> we have explored the fundamentals of containers and in the <a href="https://medium.com/@lsbenitezpereira/managing-containers-with-an-iot-platform-4e9a4293a16">second post</a> we have seen how to use an IoT Platform to ease the containers management. Now we’ll focus on how modern <strong>DevOps tools and practices</strong> can be applied to this type of project, helping to have workflows that are automated, less error-prone, and highly reproducible.</p><p>We’ll still use our little demo with Jetson Nano as an example, but this time there is zero news in the example itself: we’ll just explore the processes that surround the application. Before we dive into the tutorial, a huge thanks to the co-authors <a href="https://www.linkedin.com/in/dan-danciu/">Dan Danciu</a> and <a href="https://www.linkedin.com/in/anebz/">Ane Berasategi</a> :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mn3UJdXQEDoYONJy.jpg" /></figure><h3>What is infra as code</h3><p>Are practices and tools to automate infrastructure/operations tasks with declarative code, just as if they were software and data. That is, to turn manual procedures into executable code.</p><p>Many things can be put under this umbrella:</p><ul><li><strong>Infrastructure provisioning:</strong> create the resources on the cloud provider.</li><li><strong>Resource setup:</strong> prepare the created resources to receive the application (like installing docker).</li><li><strong>Packaging Server Templates:</strong> generate preconfigured images with all that the server will need.</li><li><strong>Pipeline setup:</strong> describe and execute automated workflows for common tasks (like code test, deployment, etc).</li></ul><h3>Infrastructure provisioning</h3><p>Our first task will be to create the IoT Hub and the Container Registry using a tool called <strong>Terraform</strong>. Terraform allow us to describe the infrastructure elements that we want, and then it will take care of provisioning those elements for us.</p><p>On your development machine (your normal computer), you’ll have to install azure CLI and Terraform. The Jetson Nano doesn’t require any additional installation.</p><p>The “database” where Terraform will store information about what is being created is a file called <strong>state file</strong>. It can be stored on your local computer, but it’s a better practice to save it on the cloud. I choose azure blob storage (could be AWS S3, Google Cloud Storage, among others), and the storage account to store it have to be created without Terraform, and in this case we’ll do it with Azure CLI. To do that, open a terminal, authenticate yourself with the Azure CLI (run az login and follow the instruction), and execute the script storage_create with bash storage_create.sh. As you can see, that script will create the storage account and storage container that we need to store our Terraform state file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fed9af0d34792b3bc3545f3bb902430/href">https://medium.com/media/2fed9af0d34792b3bc3545f3bb902430/href</a></iframe><p>Now we are ready to run Terraform itself. Go to the folder tutorial-containers-03/terraform, modify the file variables.tf to have the subscription_id and tenant_id of your azure environment (you can find those in the Azure Portal searching for Subscriptions and then for Azure Active Directory). Run terraform init to tell Terraform to install all stuff it will need.</p><p>To create the resources, just run terraform apply. Terraform will prompt you to confirm the resources that you want to create, just go ahead and type &quot;yes&quot;. As you can see in the file main.tf, there are several &quot;blocks&quot; that describe each desired element, like this one for the IoT Hub:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d56e9d3523b9039d9c5e1bef3604efd/href">https://medium.com/media/5d56e9d3523b9039d9c5e1bef3604efd/href</a></iframe><p>If everything was successful, then you will already be able to see all newly created resources at the Azure Portal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*aBmK4Pj03lOdFfDD.gif" /></figure><h3>Deployment template</h3><p>Do you remember when we manually select which modules should be deployed to Jetson, their configurations, etc? We can do the same now just writing a text file.</p><p>The “deployment template” of IoT Hub is a <strong>complete description</strong> of what modules should be deployed, in a similar way as docker-compose that we used in the first tutorial. This template can have many parameters that microsoft will use when generating the actual deployment file (that is also just another text file with json syntax), and then the configuration will be applied to the devices.</p><p>I won’t enter in detail about its syntax, please go ahead and explore it yourself. The only thing that you’ll have to change there is the field registryCredentials, with the same credentials that you used in the last tutorial.</p><h3>CI/CD pipeline</h3><p>There are two essential tasks for this tutorial: build the container and apply the deployment template. To automate those tasks we’ll use Azure Pipelines, which is part of the set of solutions called Azure DevOps.</p><p>Go to <a href="https://dev.azure.com/">Azure DevOps</a> and create a new organization (or use an existing one). Then create a new project inside that organization, and finally create a new pipeline inside that project doing the following:</p><ol><li>Go to the section Pipelines</li><li>Click New pipeline</li><li>Where is your code: Github</li><li>Select the repository</li><li>You’ll be redirected to Github to approve the connection</li><li>Configure the pipeline with the option “Existing Azure Pipelines YAML file”, selecting tutorial-containers-03/azure-pipelines.yml.</li><li>Review and create the pipeline.</li></ol><p>Now <strong>every time you push your code to Github the pipeline will be triggered</strong> and will execute the steps described in that yaml file, and you’ll see a “report” looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9TOl5YJ5Gxeoua-A.png" /></figure><p>In the following sections I’ll explain a little of the syntax of that file, as well as some configurations that still have to be done in order to run the pipeline successfully.</p><h3>Pre-build</h3><p>Before building the container images, we need to <strong>decide whether the containers should be built or not</strong>, so that we don’t build every container every time, and we’ll use the module version for that.</p><p>Up to now we informally labeled the images as “1.0”, “1.1”, etc, and now we’ll use a separate file called module.json for that. This format is an informal standard of Azure IoT, but as we have seen in the previous tutorial, you don&#39;t need to follow it. When you make changes in the code that you want to see reflected in the running containers, go to that file (inside the folder of each module) and modify its version.</p><p>But the pipeline has to “remember” if it has already built an image before, right? We’ll use Pipeline Library to that:</p><ol><li>Go to the section Pipelines</li><li>Library</li><li>Create variable group</li><li>Give it the name “Latest Image Versions”</li><li>Add two variables, “button_latest” and “led_latest”, both with the value 1.0.0</li><li>Pipeline permissions</li><li>Select our pipeline</li><li>Give permissions to the pipeline to write the variables a. security b. give Administrator permission to the user “ Build Service”</li></ol><p>You don’t need to modify anything on the script itself, and you can see that it just reads the module.json file, compare the field version with the version in the library, and then store it in the variable doBuild:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af7e06ee4b67b99e6ac9d6048d88eb73/href">https://medium.com/media/af7e06ee4b67b99e6ac9d6048d88eb73/href</a></iframe><h3>Build</h3><p>Now, <strong>build the container images and push them to the container registry</strong>. This is just the execution of a script, as we have done in the last tutorial, but first you have to give permissions to Azure Pipelines to push containers to your registry, by setting up a service connection:</p><ol><li>Project settings</li><li>Service connections</li><li>New Service Connection</li><li>Select Docker Registry</li><li>Select Azure Container Registry</li><li>Select the subscription in which you created the registry, and then the registry itself</li><li>Give it the name “acr connection”</li><li>Enable the option “grant access permission to all pipelines”</li></ol><p>For this tutorial this was not required, but we decided to also <strong>build the images for several architectures</strong>. Since we are just using a Jetson Nano, the only image that will really run is the arm64 one. If you are using a raspberry pi you can use the arm32 one, or even use the amd64 to test/debug the containers in your personal computer.</p><p>You can see that the build step is quite big, but most of it is just the “boilerplate” required to execute the main build-and-push step:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c94fc6b0b49d9b141691ba152b23144/href">https://medium.com/media/6c94fc6b0b49d9b141691ba152b23144/href</a></iframe><p>If you run the pipeline now (by committing and pushing to Github), you’ll see that all containers are built. If you access the container registry, you’ll see that the newly built images are already there.</p><h3>Deployment</h3><p>WE ARE ALMOST THERE, almost deploying to the embedded device. But first, set up connection with the IoT Hub:</p><ol><li>Project settings</li><li>Service connections</li><li>New Service Connection</li><li>Select Azure Resource Manager</li><li>Select “Service Principal (automatic)”</li><li>Select the subscription and resource group where you created the IoT Hub</li><li>give it the name “subscription-connection”</li><li>Enable the option “grant access permission to all pipelines”</li></ol><p>We’ll use the tasks of type “AzureIoTEdge@2” provided by Microsoft, specifically the two actions “Generate deployment manifest” and “Deploy to IoT Edge devices”. As I said before, we made the pipeline considering that you may need to deploy to multiple types of devices, so during this deployment step we use the “matrix” syntax to configure everything properly.</p><p>The device enrollment is still the same process as in part 2 of this tutorial, please take a look there. We won’t cover the enrollment automation, like using Device Provisioning Service (DPS) from Azure. But now <strong>you can trigger the pipeline and the whole workflow will work</strong>, building and deploying everything. This initial setup was manual, but from now on you can focus on writing the code and those manual tasks that we did in the last tutorial won’t be needed again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*5U69mkHfRr55UmeT.gif" /></figure><h3>Conclusions</h3><p>We have explored some tools to ease our “meta work”: things that are required to have the solution working, but that are not part of the core solution itself. All this may sound to you as “killing a fly with a cannon”, but those meta tasks may end up consuming a large part of your time, and definitely automation will make you more productive and happy with your work.</p><p>Before we finish, I recommend you destroy the resources if you don’t need them anymore. For Terraform it’s easy, just go to tutorial-containers-03/terraform and execute terraform destroy. The storage account was created outside Terraform so we have to destroy it with Azure CLI, doing bash storage_destroy.sh</p><p>I think this is the last tutorial of this series, but feel free to ask us questions or request tutorials that you would like to see here.</p><p>Bye bye and happy coding :)</p><h3>References</h3><p>[1] Infrastructure as Code. Kief Morris. O’Reilly, 2016.</p><p>[2] Continuous integration and continuous deployment to Azure IoT Edge devices. Microsoft documentation, available at: <a href="https://docs.microsoft.com/en-us/azure/iot-edge/how-to-continuous-integration-continuous-deployment?view=iotedge-2020-11">https://docs.microsoft.com/en-us/azure/iot-edge/how-to-continuous-integration-continuous-deployment?view=iotedge-2020-11</a></p><p>[3] Using CI/CD to Deploy IoT Edge Modules with Confidence. Microsoft Developer youtube channel. Available at: <a href="https://www.youtube.com/watch?v=Ifst1k1lD7A">https://www.youtube.com/watch?v=Ifst1k1lD7A</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb8921909c4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing containers with an IoT Platform]]></title>
            <link>https://medium.com/@lsbenitezpereira/managing-containers-with-an-iot-platform-4e9a4293a16?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e9a4293a16</guid>
            <category><![CDATA[azure-iot-hub]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[jetson-nano]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 02:12:52 GMT</pubDate>
            <atom:updated>2022-03-11T16:47:25.205Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is the second of a series about using containers for embedded systems, where in the <a href="https://medium.com/@lsbenitezpereira/containers-for-embedded-systems-7c5929bacf1e">first post</a> we have explored the fundamentals of containers. Now we’ll focus on using an IoT Platform (specifically, <strong>Azure IoT Hub</strong>) to ease the management of large embedded applications.</p><p>We’ll keep using our little practical demo with a Jetson Nano (but you can reproduce the tutorial in any Linux device) and we’ll demonstrate some of the platform capabilities using azure’s web UI (called Azure Portal). All code and steps to reproduce them are in <a href="https://github.com/LeonardoSanBenitez/containers-for-embedded-systems">this git repository</a>. And before we start, a huge thanks to the co-authors <a href="https://www.linkedin.com/in/dan-danciu/">Dan Danciu</a> and <a href="https://www.linkedin.com/in/anebz/">Ane Berasategi</a> :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9O5s5yZR3R5c3fiP.png" /></figure><h3>What is an IoT Platform</h3><p>It’s a system that “provides abstraction across the multitude of diverse devices and data sources in addition to allowing for the management and control of a range of systems and processes” (Rayes, 2019). That is, <strong>ease development and management of IoT project</strong>, even if we need to handle thousands of devices around the world with each of them running several applications/microservices.</p><p>In this tutorial we’ll use Azure IoT Hub mainly to centrally control which containers should be running in each device, debug the application remotely, and easily add/remove devices for our fleet. However, most IoT platforms (like IoT Greengrass or IBM Watson IoT) also will provide at least some of the following features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44ceda389c16908d2058e2e17cf38f9a/href">https://medium.com/media/44ceda389c16908d2058e2e17cf38f9a/href</a></iframe><h3>IoT Hub setup</h3><p>Before you start with IoT Hub you’ll need an <a href="https://azure.microsoft.com/en-us/free/">azure account</a>. Please note that the following setup may incur charges to your account, so take a look at the <a href="https://azure.microsoft.com/en-us/pricing/details/iot-hub/">Azure IoT Hub pricing</a>.</p><p>Now access the Azure Portal and create an IoT hub:</p><ol><li>Search for IoT Hub</li><li>Hit Create</li><li>In “Resource group”, create a new one</li><li>Give a descriptive name to your IoT Hub (mine was tutorial-containers)</li><li>If you don’t need to change anything else (like the tier, in the management section, that will affect the pricing), just click on Review + Create</li></ol><p>It may take some time to create, but you can proceed with the tutorial while that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*ODwNvXI46-Q2qylI.gif" /></figure><h3>Container build</h3><p>Our containers won’t build themselves when deploying, we need to <strong>build them beforehand</strong> and store their images somewhere. I’ll store them in Azure Container Registry, but it could also be Docker Registry, AWS ECR, etc. To create one, access the Azure Portal and:</p><ol><li>Search for Container registries</li><li>Hit Create</li><li>Select the same resource group as before</li><li>Give it a name (mine was tutorialcontainers), then click in Review + Create.</li></ol><p>You’ll need to take note of some values to use them later: Login server (in the Overview section), usarname and password (in the Access keys section).</p><p>As we are using ARM32 images, <strong>the easier way to build those images is in an ARM32 device</strong>, so ssh into your Jetson and build the containers there. Note the only change in the code was the container name from “led” to “led-acr” to avoid conflicts if you have done the first part of this tutorial. Now just substitute the values that you took note before in <a href="https://github.com/LeonardoSanBenitez/containers-for-embedded-systems/blob/main/tutorial-containers-02/build_push.sh">this script</a> and execute it. It will log in to the registry, build, tag, and push both docker images.</p><p>In case you are wondering, we use the IMAGE_VERSION variable (in the script) because the edge device will pull new images from the registry only when there is in the registry an image with a higher version than the device have locally. Therefore, if you want to build different versions of your images, you need to change the version to indicate which should be downloaded by the edge device.</p><h3>Device enrollment</h3><p>The IoT devices have to be <strong>onboarded to IoT Hub</strong> to be managed by the platform. Once this is done, all management can be done from the cloud. There are several ways to perform this onboarding, we’ll use the easier. This section is a summary of <a href="https://docs.microsoft.com/en-us/azure/iot-edge/how-to-register-device?view=iotedge-2020-11&amp;tabs=azure-portal">this Microsoft documentation</a>, and there you’ll also find more information about the other deployment methods.</p><p>Now go to the Azure Portal and:</p><ol><li>Select the created IoT Hub</li><li>Go to IoT Edge, then Add Iot Edge Device</li><li>Choose a descriptive name (I chose dev-leonardo-01)</li><li>Authentication type: Symmetric key</li><li>Auto generate keys: yes</li><li>Connect this device to an IoT hub: enable</li><li>Save</li></ol><p>Go back to “IoT Edge”, select your device and take note of the primary connection string. After the cloud-side setup, we need to perform the device-side setup. Substitute the connection string in <a href="https://github.com/LeonardoSanBenitez/containers-for-embedded-systems/blob/main/tutorial-containers-02/device_configuration.sh">this script</a> and execute it. It basically installs IoT Edge on the device and configures it so it can connect with IoT Hub on the cloud.</p><p>You may have to wait a few minutes for everything to be configured, but soon you’ll see on the portal your device with the status “417 — The device’s deployment configuration is not set”. Don’t worry, the error message will disappear after the next LAST step, go go!</p><h3>Module deployment</h3><p>Your device is now ready to be <strong>controlled from the cloud</strong>, so let’s do something!</p><p>The configuration is done using JSON descriptions of the containers that should be running on the device: what images, volumes, port mapping, etc. I won’t enter in details about those configurations, maybe in a future tutorial, but you can find more in <a href="https://docs.microsoft.com/en-us/azure/iot-edge/how-to-use-create-options?view=iotedge-2020-11">microsoft’s</a> and <a href="https://docs.docker.com/engine/api/v1.32/#operation/ContainerCreate">docker’s</a> documentation.</p><p>Now go to your IoT Hub in the Portal and:</p><ol><li>Enter in IoT Edge</li><li>Select your device</li><li>Click Set Modules, Add, IoT Edge module</li><li>Add our “button” module<br>- Name: “button-acr”<br>- Image URI: “tutorialcontainers.azurecr.io/button-acr:1.0”<br>- Container Create Options:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a82ea6c3ca491cc4f0ec7b4223ee1ec0/href">https://medium.com/media/a82ea6c3ca491cc4f0ec7b4223ee1ec0/href</a></iframe><p>5. Add our “led” module<br> - Name: “led-acr”<br> - Image URI “tutorialcontainers.azurecr.io/led-acr:1.0”<br> - Container Create Options:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebc097557e7d25b3c1de69679cc8071d/href">https://medium.com/media/ebc097557e7d25b3c1de69679cc8071d/href</a></iframe><p>6. Review and create, Create</p><p>And your device is enrolled!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*7oxgY2XjCU2biWUu.gif" /></figure><h3>Advantages of an IoT Platform</h3><p>May take a few minutes to download and run the images. Just grab a coffee and wait, soon you’ll have all containers running just as we had in the <a href="https://medium.com/@lsbenitezpereira/containers-for-embedded-systems-7c5929bacf1e">first tutorial</a>! But… what is the difference?</p><ul><li><strong>Remote log centralization</strong>: the execution logs of your application, which are precious to debugging and monitoring, are now immediately available on the Portal (just select your device and click in “Troubleshoot”), something that usually would require accessing each device directly.</li><li><strong>Configuring the containers remotely</strong>: in the last section you set the modules just by writing some parameters in the Portal, and the edge device received those instructions and made the required changes to itself. As your application will probably be updated, patched, and refactored several times, that functionality can be extremely useful.</li><li><strong>Device management</strong>: now you can easily disable devices, rotate cryptographic keys, check the device state in real-time, among several other management features. Those management tasks may sound trivial if you have one device, but will consume a huge amount of time if you have a fleet of devices in production.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*vkcWztgOPrCcA6RQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tql125uRVXx2ObT1.png" /></figure><p>All those features came “for free”, we didn’t did any changes to the code. But Azure IoT solutions offer many many more features, <strong>including ones that could greatly ease our coding</strong>: communication between modules and between devices, message routing, plug-and-play access to third-party modules, etc.</p><h3>Conclusion</h3><p>There are many advantages in using an IoT Platform, but it can also be complicated and — even if you learn it well — have several steps/processes to get everything right. <strong>This complexity is common in modern IT infrastructures</strong>, but we can ease our own work in many ways: provision infrastructure resources from code, write pipelines for repetitive tasks (like building containers), use the azure command-line interface instead of the Portal, among several others.</p><p>In the <a href="https://medium.com/@lsbenitezpereira/streamline-iot-projects-with-infrastructure-as-code-eb8921909c4c">next tutorial</a> we’ll see how modern <strong>DevOps tools and practices</strong> can be applied to embedded systems projects, helping to have workflows that are automated, less error-prone, and highly reproducible.</p><p>Stay tuned!</p><h3>References</h3><p>[1] Internet of Things: From Hype to Reality. Ammar Rayes and Samer Salam. Springer, 2016.</p><p>[2] IoT Platforms: What They Are &amp; How To Select One. Brian Ray. Link-labs, 2016. Available at: <a href="https://www.link-labs.com/blog/what-is-an-iot-platform">https://www.link-labs.com/blog/what-is-an-iot-platform</a></p><p>[3] Embedded System Design. Peter Marwedel, Springer, 2018.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e9a4293a16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containers for embedded systems]]></title>
            <link>https://medium.com/@lsbenitezpereira/containers-for-embedded-systems-7c5929bacf1e?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c5929bacf1e</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[jetson-nano]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 01:47:41 GMT</pubDate>
            <atom:updated>2022-03-11T16:46:46.866Z</atom:updated>
            <content:encoded><![CDATA[<p>In this series of posts we’ll explore <strong>why and how</strong> to use containers in embedded systems, a combination that is still not common. Along the series we’ll use a <strong>Jetson Nano</strong> development kit to do small demonstrations (but you can easily reproduce them in other devices like a raspberry pi), and all code and steps to reproduce them are in <a href="https://github.com/LeonardoSanBenitez/containers-for-embedded-systems">this git repository</a>.</p><p><strong>Our goal</strong> with this series is twofold:</p><ul><li>For you that still don’t use containers, to give you a head start in conceptual understanding and code to be reused in your work;</li><li>For you that already use containers, to discuss best practices and tools to ease your work.</li></ul><p>In this first post, we’ll see the fundamentals of containers and present our “hello world” demo that we’ll use throughout the series. But before we start, a huge thanks to the co-authors <a href="https://www.linkedin.com/in/dan-danciu/">Dan Danciu</a> and <a href="https://www.linkedin.com/in/anebz/">Ane Berasategi</a> :)</p><p>Fasten your belt, grab a coffee, and let’s start!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ViQr9phO5vqDtQh5xR2fw.png" /></figure><h3>What are embedded systems</h3><p>They are dedicated processing systems within a larger mechanical or electrical system, usually an enclosed product sold as a whole. Some examples are ABS controller, smart fridge interface, aviation autopilot: you won’t buy those things separately, they are embedded in larger products.</p><p>Embedded systems usually have strong requirements of performance, reliability, and production costs, posing unique challenges to developers and engineers. When these computing enabled devices are connected to the Internet we usually use the term Internet of Things, which also sounds much nicer ;)</p><h3>What are containers</h3><p>They are a method for packaging, distributing, and running applications. Their main characteristic is that they can <strong>isolate processes</strong> from the operating system: dedicated memory, networking, namespaces, etc.</p><p>Sounds like a Virtual Machine, right? Yes, but one big difference is that containers share the operating system kernel of their host system, therefore they are lightweight. A direct consequence of that sharing is that containers can’t run a different OS (like running a Linux container on top of a Windows host), and can at most run different distributions of the same OS (like running a CentOS container on top of an Ubuntu host).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*kOTRGK1hCoQDLuNm.png" /><figcaption><em>Difference between Virtual Machines and Containers (Source: Docker)</em></figcaption></figure><p>Some important concepts: a <em>container</em> is a running instance of this isolated environment, being managed by a <em>container engine</em>. A container is started having as a base an <em>image</em>, a binary file with everything bundled together. An image can be <em>built</em> from a <em>definition file</em>, a text description of what goes inside the container.</p><p>But “container” is just an abstract concept, and there are many softwares that implements it. The most well-known container engine is called <strong>docker</strong>, and from now on we’ll use both terms as synonyms.</p><h3>Why use containers</h3><p>There are many advantages in using containers for any application, but we want to highlight things that are especially relevant in the context of embedded systems:</p><ul><li><strong>Simplify software development</strong>: different developers can work in the same system with less interference between them. Each container can have different dependencies installed, have different toolchains, be built independently, etc.</li><li><strong>Simplify testing</strong>: each container is an isolated system, so you spend less time worrying about the configurations of your test setup. For the same reason, you can easily test the system in several different underlying configurations, something that in a non-container environment would probably require using several different devices.</li><li><strong>Ease remote (over-the-air) updates</strong>: you can store all container images in a central repository and update the application (or just part of the application) simply by stopping and starting a new container instance.</li><li><strong>Quicker device setup</strong>: setting up a fresh device requires only installing docker. Even when the OS is patched, updated, or maybe completely replaced, the setup procedure will likely remain unchanged.</li></ul><p>As nothing is perfect, you need to be aware of some disadvantages:</p><ul><li><strong>Increase in resource usage</strong>: containers do have an overhead compared with using just the OS. If your device is already at the limit of its performance, you may have to reconsider using containers.</li><li><strong>Container-capable device</strong>: containers require a device capable of running containers (dããã), which basically means a device with Linux. This may sound trivial to some software developers, but many embedded devices use only an RTOS (real-time operating system) or no OS at all.</li><li><strong>Complexity and learning curve</strong>: you probably already have a well-defined tooling to build your system, like Yocto, and to start using containers will add one more layer of complexity to this workflow. Also, you may need to manage several containers running on the same device, configure the workflows for building the container images, and so on.</li></ul><h3>Our little demo</h3><p>Guess what? IT’S A BLINK LED!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*mJgrZ-KAVRMJBJtN.gif" /></figure><p>Okay, almost. We’ll demonstrate the isolation feature of containers by breaking the traditional “blink led” example into <strong>two independent modules</strong>: one will read a button every one second and the button’s state (pressed or not) to the second module, which will turn on the led if the button is pressed.</p><p>The communication happens over HTTP: the first module initiates the request and the second is a web server waiting for requests. The modules are completely independent, could easily be developed by different persons, be written in different programming languages, and even have their proprietary source code hidden from each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*2WiumpYuC-VOmmlR" /><figcaption><em>Demo with a button and led from Sparkfun, running on a Jetson Nano (inside the case).</em></figcaption></figure><p>Each image is described by a definition file named Dockerfile, that looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/161570dfde7bd40c480d90de449beea9/href">https://medium.com/media/161570dfde7bd40c480d90de449beea9/href</a></iframe><p>That is, take a base image that already has python 3.7 installed ( FROM...), then install the python dependencies for this project ( pip install...), copy the source code to inside the containers ( COPY...), and finally start our code ( python3...). The code itself is even simpler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e1cf7456a1914cbd7b06d47defe99c5/href">https://medium.com/media/8e1cf7456a1914cbd7b06d47defe99c5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08a24b701a08d17993e6a255241b8974/href">https://medium.com/media/08a24b701a08d17993e6a255241b8974/href</a></iframe><p>The first sends one HTTP request per second ( requests.post...) and the second is a FastAPI webserver that is first initiated ( uvicorn.run...) and then listens to HTTP POST requests (@app.post(&quot;/{state}&quot;)...) to turn the led on or off ( my_button.LED_on...).</p><p>We are using an extension of docker called <em>docker-compose</em> to handle the two containers together, to <em>orchestrate</em> them. Once you have docker and docker-compose installed <strong>in the device</strong> (following <a href="https://github.com/LeonardoSanBenitez/containers-for-embedded-systems/blob/main/init_os.sh">this instructions</a>), you can execute the command docker-compose up in the folder &quot;tutorial-containers-01&quot; to build and start running both containers.</p><p>Congratulations, you now have two containers working together in your embedded device :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*bYn5-mGlKF06OKNv.gif" /></figure><h3>Conclusion and next steps</h3><p>We have seen the basics of containers and how this technology can be useful to embedded systems, but there is still a lot to be explored. In the <a href="https://medium.com/@lsbenitezpereira/managing-containers-with-an-iot-platform-4e9a4293a16">next post</a> we will see how the usage of an <strong>IoT platform</strong>, specifically Azure IoT Hub, to manage embedded systems built with containers.</p><p>Stay tuned ;)</p><h3>References</h3><p>[1] Embedded System Design. Peter Marwedel, Springer, 2018.</p><p>[2] Docker documentation. Available at: <a href="https://docs.docker.com/get-started/resources/">https://docs.docker.com/get-started/resources/</a></p><p>[3] Why the future of embedded software lies in containers. Till Adam, Embedded, 2021. Available at: <a href="https://www.embedded.com/why-the-future-of-embedded-software-lies-in-containers/">https://www.embedded.com/why-the-future-of-embedded-software-lies-in-containers/</a></p><p>[4] Containers on Linux embedded systems. Sandra Tobajas, Savoirfairelinux, 2020. Available at: <a href="https://blog.savoirfairelinux.com/en-ca/2020/containers-on-linux-embedded-systems/">https://blog.savoirfairelinux.com/en-ca/2020/containers-on-linux-embedded-systems/</a></p><p>[5] Using containers on embedded Linux. Sergio Prado, Embeddedbits, 2021. Available at: <a href="https://embeddedbits.org/using-containers-on-embedded-linux/">https://embeddedbits.org/using-containers-on-embedded-linux/</a></p><p>[6] How Linux Containers can Help to Manage Development Environments for IoT and Embedded Systems. Yan Vugenfirer &amp; Dmitry Fleytman, The Linux Foundation. Available at: <a href="https://www.youtube.com/watch?v=F61MM_uuI5A">https://www.youtube.com/watch?v=F61MM_uuI5A</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c5929bacf1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision zero to hero: A tutorial about coin recognition]]></title>
            <link>https://medium.com/@lsbenitezpereira/computer-vision-zero-to-hero-a-tutorial-about-coin-recognition-60dec3126728?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/60dec3126728</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 20:35:25 GMT</pubDate>
            <atom:updated>2020-11-13T20:35:25.280Z</atom:updated>
            <content:encoded><![CDATA[<p>Computer vision is interesting, huh? Have you seen the demonstrations of Pulse [1] or NVIDIA Maxine [2]?<br>However, it’s common when there are no trained models for your task, no benchmark datasets, no easy to follow tutorials, and you don’t have a whole team to develop wonderful machine learning models.</p><p><strong>How to achieve, in a very short time and with little prior knowledge, acceptable results that may serve as proof of concept?</strong> In this tutorial you’ll learn this process end to end, following a practical example about coin recognition.</p><p>And, before anything else, I would like to thank <a href="https://www.linkedin.com/in/igor-debastiani/">Igor Debastiani</a> for coauthoring this article and for being the <strong>main developer</strong> of practical part of this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*sv53MLdmmu_lcaJc" /><figcaption>Photo from <a href="https://unsplash.com/photos/UbJMy92p8wk">Amanda Dalbjörn</a></figcaption></figure><h3>Reducing the scope</h3><p>Our objective is simple: to identify Brazilian coins. <br>Well… it’s not that simple: there are 4 different types of coin, that can be rusted or in bad condition, that may be partially occluded in the photo, the scenes can vary greatly in illumination, among other challenges.<br>So we decided to reduce the scope of the project to the bare minimum, the simplest feature that could demonstrate that the idea could work: to identify one type of coin (the one of 1 Brazilian real, as shown below), under normal indoor lighting, in clear and “easy” photographs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*f8JXMNxY66NB043I" /></figure><h3>Choosing the technologies</h3><p>What will we use? Which languages, frameworks, development environments? <br>We are looking for technologies easy to understand, with acceptable results, with good documentation and tutorials. You may change it in the future when faced with constraints like computational performance or easiness to deploy, but now the focus is just to prove that your project can be done. We don’t need to reinvent the wheel. <br>Among several options, the framework ImageAI [3] fits well our needs: it is easy to learn, very little boilerplate, very good documentation and spectacular results. Comparing to other libs, ImageAI was the easiest to learn and with the best results. <br>To label de dataset, we chose the library labelImg [4] because it is an open-source solution with an easy learning curve and had all the functionalities needed.</p><h3>Labeling a dataset</h3><p>You already defined your scope, now: <strong>what type of data do you need to represent the information you want?</strong><br>In our case will be enough to have photos of several coins on the table and on our hand, taken with a cellphone camera (today’s cellphone have nice cameras to do tasks like this), with bounding boxes around the one of 1 real (1BRL).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*zJ3WkQ_ORltY1Wvn.png" /></figure><p>We decided to annotate 250 images, but it was just a guess: you may need more, you may need less, you may have to label more data after trying to train the model and not achieving good enough results, it depends. <br>We’ll use this data to train our model, but how we’ll know how well it will be when faced with new data, in a real situation? <br>We may want to label more data in the future and compare the model’s predictions with our own labels. It’s a good idea, but why not label this “test dataset” just now? Even better, why not just hold out part of the already labeled dataset, excluding it from training and using it only for testing? This methodology is called Cross Validation, and is widely used throughout the Machine Learning field.<br>Word of advice: The labeling process is very long and trust me, this needs to be done right. So take your time, put some music on and do this with attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_td7-lEbI9XmoSPY.png" /></figure><h3>Training a model</h3><p>You don’t want, now, to spend much time training or to pay a small fortune in cloud computing. Furthermore, you don’t want to perform a careful fine-tuning in the model, you just need an acceptable precision (that, for most problems, is much lower than the state of the art). After the environment setup, <strong>the code itself is just 6 lines</strong> (declare the neural network architecture to be used, point to the data, set hyperparameters, start training):</p><pre>from imageai.Detection.Custom import DetectionModelTrainer</pre><pre>trainer = DetectionModelTrainer()<br>trainer.setModelTypeAsYOLOv3()<br>trainer.setDataDirectory(data_directory=”hololens”)<br>trainer.setTrainConfig(object_names_array=[“hololens”], batch_size=4, num_experiments=100, train_from_pretrained_model=”pretrained-yolov3.h5&quot;)<br>trainer.trainModel()</pre><p>We’ll use a famous architecture, YoloV3, pretrained on a famous dataset, ImageNet. This will speed up the training and make it easier to get good results, that is exactly what we want. Comparing with this <a href="https://imageai.readthedocs.io/en/latest/customdetection/">example</a> of the ImageAI library, they’ve used 400 epochs in a dataset of 300 images, taking 300s per epoch. In our case, we used 30 epochs with 3000s each. WHY? Because our images were HUGE, and the higher the resolution the higher will be the training time. Lesson learned: use images as clear as you can get and with a resolution that captures all the details you need, but NOT MORE than that. <br>Notice: The relation 1epoch/3000s is based on my computer. Assuming that the example on the ImageAI docs was made on a home computer also, the previous assertion is true. If not, my advice is still the same: images big enough only to capture the details you need. The time consumed per epoch will be lower, but not in the same proportion as the one I compared before. <br> <br>Well… And how many epochs did I need? <br>Since the ImageAI lib itself will change the machine learning parameters, the more the better. A good number, to start, is 25. Then you will need to run an evaluation script, which will use the test images to verify the precision of our model. Doing that, with 25 epochs, the precision obtained in the process was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*Rxq2YUtb1wzDIBz6.png" /></figure><p>Which we can see that started very poorly but improved until the peak value of 0.87 on the 20th epoch.</p><h3>Reporting and communicating</h3><p>For proof of concept, we have already achieved a lot. Our model doesn’t need human-level precision to be useful: if it can save time or help someone to do its job, it already worth the effort<br>So it’s DONE!!<br>Not yet.<br>If you want to keep working on the model (and there is still a lot of room for improvements), you’ll probably have to convince others that your time worth the effort. Particularly to coin recognition, machine learning probably is the best approach to follow, but for most real problems the decision is much less clear, so you have to carefully analyze your results and the methodology that led to them in order to decide how to continue.<br>Here are some post-development tips:</p><ul><li>Clearly identify the procedures done to get your results (something like what we are doing here);</li><li>Explain your evaluation metrics, and what they mean in a practical context;</li><li>Understand what you’ve done, in case you didn’t before. This is not an extensive tutorial in theoretical background, but we highly recommend you to go deeper and understand what was done;</li><li>Show that this was just an initial result and point out some directions for future works.</li><li>Organize all this in a slide presentation, online dashboard, some easy-to-read document, repo’s readme, anything like that.</li></ul><h3>References</h3><p>[1] — S. Menon, A. Damian, M. Hu, N. Ravi, and C. Rudin (2020). PULSE: Self-Supervised Photo Upsampling via Latent Space Exploration of Generative Models. The IEEE Conference on Computer Vision and Pattern Recognition (CVPR). <a href="http://pulse.cs.duke.edu/">http://pulse.cs.duke.edu/</a></p><p>[2] — NVIDIA (2020). The NVIDIA Maxine. <a href="https://blogs.nvidia.com/blog/2020/10/05/gan-video-conferencing-maxine/">https://blogs.nvidia.com/blog/2020/10/05/gan-video-conferencing-maxine/</a></p><p>[3] — Moses and J. Olafenwa (2018). ImageAI, an open source python library built to empower developers to build applications and systems with self-contained Computer Vision capabilities. <a href="https://github.com/OlafenwaMoses/ImageAI">https://github.com/OlafenwaMoses/ImageAI</a>.</p><p>[4] — Tzutalin (2015). LabelImg. Git code. <a href="https://github.com/tzutalin/labelImg">https://github.com/tzutalin/labelImg</a></p><p>[4] — Tzutalin (2015). LabelImg. Git code. <a href="https://github.com/tzutalin/labelImg">https://github.com/tzutalin/labelImg</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60dec3126728" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natureza; Ritmo circadiano; Ritmo de trabalho.]]></title>
            <link>https://medium.com/@lsbenitezpereira/natureza-ritmo-circadiano-ritmo-de-trabalho-bf9c0be6037c?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf9c0be6037c</guid>
            <category><![CDATA[produtividade]]></category>
            <category><![CDATA[felicidade]]></category>
            <category><![CDATA[natureza]]></category>
            <category><![CDATA[bem-estar]]></category>
            <category><![CDATA[rotina]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 03:13:06 GMT</pubDate>
            <atom:updated>2020-04-21T03:13:06.865Z</atom:updated>
            <content:encoded><![CDATA[<p>Durante os meses que morei na Finlândia tive a oportunidade de ir para o extremo norte do país para caçar a Aurora Boreal, dita um dos fenômenos naturais mais belos da natureza. A minha caçada foi fracassada e eu não tive sorte de ver a Aurora, mas pelo menos me deu um bom gancho para falar do tema de hoje.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kwTCoZ4bGLcQaS5y_jGYg.jpeg" /><figcaption>Fonte: <a href="https://pixabay.com/photos/aurora-polar-lights-northen-lights-1185464/">Noel Bauza, Pixabay</a></figcaption></figure><p>Finlandeses gostam muito de atividades <em>outdoor</em>: eles são a nação mais fisicamente ativa da União Europeia [1], precisamente. Certo dia fui correr ao redor do lago onde morava e, para minha surpresa, vi bastante gente fazendo o mesmo, embora fosse um dia super úmido e nublado. Famílias inteiras fazendo piquinique, <em>macarra</em> (salsicha na grelha), exercício físico, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqCsimWRVb6SYXBvAEl6kw.jpeg" /><figcaption>Fonte: autoria própria</figcaption></figure><p>Em outra ocasião eu participei da <em>Syyspatikka</em>, a última trilha do outono, com um grupo local de escoteiros. Novamente: dia úmido, frio, mas dezenas de pessoas se reuniram para passar um tempo “juntas” (dentro da percepção finlandesa de proximidade) e em meio a natureza.</p><p>Nessa ocasião os dias já estavam consideravelmente mais curtos: amanhecia em torno de 9hs e anoitecia perto das 16hrs. Gradualmente as horas de sol diminuiriam ao longo do próximos meses, e em algumas regiões não haveria mais sol nenhum durante várias semanas. O ritmo circadiano desse povo merece ser estudado [2,3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uREBo6NL9ZldajHfkPa8og.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofjk517giC6Sy_u2B1t-xw.jpeg" /><figcaption>Fonte: autoria própria</figcaption></figure><p>Uma última historinha: finlandeses e seu curioso ritmo de trabalho. O horário do cafezinho é <strong>sagrado</strong>. Todos os dias perto das 15hrs todos se reúnem na sala do café, para falar de qualquer coisa que não seja trabalho. Se você não quiser interromper o que está fazendo, eles (no plural) vão educadamente recomendar que você dê um tempo para refrescar as ideias. E vários exemplos similares estão presentes na rotina deles: trabalhar com seriedade, mas com um ritmo saudável e respeitando a divisão trabalho-vida pessoal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*biTkIpECxit_5O6OgmszZQ.jpeg" /><figcaption>Fonte: autoria própria</figcaption></figure><p>O que esses três relatos têm em comum? Nada, rsrs. Eu quero chegar em algum lugar com isso? Sim. No nosso afã diário por resultado muita vezes esquecemos que o bem-estar é fundamental para nossa produtividade, e que a nossa relação com o ambiente ao nosso redor (entenda <em>ambiente</em> incluindo porém não se limitando à <em>natureza</em>) exerce gigante influência sobre como nos sentimos.</p><p>Shawn Achor aponta no livro <em>The Happiness Advantage</em> [4] que adota uma rotina voltada para o bem-estar e crescimento pessoal promove um grande aumento na produtividade no trabalho, na qualidade das relações interpessoais e na capacidade de convencer e comunicar ideias (o que novamente aumenta a produtividade e acelera o progresso profissional). Dessa forma, um ritmo de vida saudável não deve ser apenas uma recompensa depois de muito esforço: devemos nos dedicar ativamente à construirmos uma rotina saudável, pois todos os outros aspectos da nossa vida dependem disso.</p><h3>Referências</h3><p>[1] — <a href="https://www.goodnewsfinland.com/finland-scores-highest-in-eu-in-happiness-and-physical-activity/">https://www.goodnewsfinland.com/finland-scores-highest-in-eu-in-happiness-and-physical-activity/</a></p><p>[2] — <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3793275/">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3793275/</a></p><p>[3] — <a href="https://www.nature.com/articles/srep39976">https://www.nature.com/articles/srep39976</a></p><p>[4] — Achor, S. (2010). <em>The happiness advantage: The seven principles of positive psychology that fuel success and performance at work</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf9c0be6037c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Des-progresso ordenado: como uma cultura destrói a sua ciência]]></title>
            <link>https://medium.com/@lsbenitezpereira/des-progresso-ordenado-como-uma-cultura-destr%C3%B3i-a-sua-ci%C3%AAncia-dcbdf97bfe39?source=rss-7dd1d19bcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcbdf97bfe39</guid>
            <category><![CDATA[tecnologia]]></category>
            <category><![CDATA[ciencia]]></category>
            <category><![CDATA[tecnologia-y-sociedad]]></category>
            <dc:creator><![CDATA[Leonardo Benitez]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 23:23:05 GMT</pubDate>
            <atom:updated>2020-04-14T14:41:53.214Z</atom:updated>
            <content:encoded><![CDATA[<p>Este é um breve ensaio sobre a história do retrocesso humano: como grandes civilizações deixaram de ser grandes, como sociedades tecnologicamente avançadas se tornaram atrasadas, como algumas culturas que antes incentivavam o desenvolvimento científico passaram a inibir-lo.</p><p>Ou seja, como podemos retroceder, andar para trás (não para ganhar impulso), sabotarmos o nosso próprio desenvolvimento. Já alerto que esse texto é altamente baseado no livro <em>Armas, Germes e Aço</em> de Jared Diamond, o qual faz uma análise muito mais rigorosa do que eu sobre os destinos das sociedades humanas. Não existe uma equação matemática para modelar o progresso humano, então irei tomar alguns exemplos para discutirmos.</p><p>A <strong>China</strong>, uma das mais antigas civilizações do mundo, foi berço de uma longa lista de invenções: pólvora, papel, bússola, técnicas de fundição de ferro, entre muitas outras. Até meados de 1400 ela era muito mais avançada do que a Europa, mas algo se perdeu nos séculos seguintes. Sim, hoje a China é um dos países mais ricos do mundo, mas no começo do século 20 era uma nação pobre, em declínio e fortemente dominada por países estrangeiros [2,3].</p><p>Ou seja, a China foi uma das civilizações mais avançadas do mundo mas “não foi capaz de realizar o que é conhecido como uma revolução científica“ [4, tradução própria] e perdeu a liderança. O que causou isso? Jared Diamond dá algumas dicas ao apontar que <strong>uma sequência de governantes autoritários e conservadores se opuseram ao desenvolvimento científico</strong>, e entre seus exemplos estão frotas de navios que foram desmanteladas por causa de disputas políticas (parecidas ao moderno “não daremos continuidade à nada feito no governo anterior”) e projetos de máquinas de fiar movidas à agua que pararam de ser desenvolvidos por decisões de governantes. Outros autores apontam outras razões, como restrições de comércio e produção industrial impostas por algumas dinastias objetivando estimular a agricultura e a produção de alimentos [5].</p><p>Outro exemplo vêm do <strong>Oriente Médio</strong>, que durante a idade média foi tecnologicamente muito avançado, aberto à inovação, e com índices de alfabetismo e riqueza muito superiores à Europa no mesmo período (faço muitas comparações com a Europa, mas poderia perfeitamente fazer com outras regiões do mundo). Assim como no caso chinês podemos atribuir ao oriente médio incontáveis desenvolvimentos, da trigonometria à química, mas isso mudou com a ascensão de uma escola filosófica/religiosa profundamente oposta à ciência e à racionalidade [6], com um pensamento que prefere explicar a chuva como sendo “[…] criação divina ao invés de evaporação causada pelo sol que se condensa” [7]</p><p>Inúmeros outros exemplos existem:</p><ul><li>O Japão que, após ser o maior produtor e detentor de armas de fogo do mundo em 1600, abandonou quase completamente a pólvora por causa de uma classe dominante samurai que via nela uma ameaça à sua cultura de armas de corte [1, pg. 258];</li><li>Aborígenes da Tasmânia, que abdicaram da pesca e ferramentas de osso (importantes tecnologias para produção de alimento) para voltarem a serem coletores e caçadores; [1]</li><li>Aborígenes da Austrália que, apesar de terem no passado dominado o uso de arco e flecha, também optaram por abandonar essa tecnologia. [1]</li></ul><p>Veja bem, o problema não é de uma religião ou outra, esse partido político ou aquele. <strong>O retrocesso de uma sociedade acontece pelo repúdio aos métodos da inovação e do desenvolvimento científico, por uma visão de mundo incompatível com o progresso.</strong></p><p>Por fim, deixo algumas provocações: o que mais retrocede? A qualidade da nossa democracia está ficando pior? Será que a qualidade da política de países com uma história democrática muito maior do que a nossa — como por exemplo os Estados Unidos (nós somos uma democracia desde 1989, eles desde 1776) — também está piorando? Será que a capacidade intelectual de um cidadão mediano, nossa “inteligência”, também está diminuindo? Em caso afirmativo, como podemos reverter essas tendências?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrw7soS5KD5qgapLfxaJxA.jpeg" /><figcaption>Foto de Helsinki, capital da Finlândia. Esse já foi um país muito pobre, um dos mais pobres da Europa, mas reverteu sua tendência por meio de investimento em educação e ciência. Autoria Própria.</figcaption></figure><h3>Referências</h3><p>[1] — Jared Diamond. Guns, Germs, and Steel. W. W. Norton &amp; Company, 1997.</p><p>[2] — History Learning Site, 2020. Disponível em: <a href="https://www.historylearningsite.co.uk/modern-world-history-1918-to-1980/china-1900-to-1976/china-in-1900/">https://www.historylearningsite.co.uk/modern-world-history-1918-to-1980/china-1900-to-1976/china-in-1900/</a></p><p>[3] — Wikipedia. Economic history of China (1912–49), 2020. Disponível em: <a href="https://en.wikipedia.org/wiki/Economic_history_of_China_(1912%E2%80%9349)">https://en.wikipedia.org/wiki/Economic_history_of_China_(1912%E2%80%9349)</a></p><p>[4] — Economic History Association, 2020. Disponível em: <a href="https://eh.net/encyclopedia/economic-history-of-premodern-china-from-221-bc-to-c-1800-ad/">https://eh.net/encyclopedia/economic-history-of-premodern-china-from-221-bc-to-c-1800-ad/</a></p><p>[6] Fu Zhufu. The Economic History of China: Some Special Problems. Sage Publications. Modern China, Vol 7 No 1, 1981. Disponível em: <a href="https://journals.sagepub.com/doi/abs/10.1177/009770048100700101?journalCode=mcxa">https://journals.sagepub.com/doi/abs/10.1177/009770048100700101?journalCode=mcxa</a></p><p>[6] — Hillel Ofek. Why the arabic world turned away from science. The New Atlantis.</p><p>Hillel Ofek. Why the Arabic World Turned Away from Science. The New Atlantis, Number 30, Winter 2011, pp. 3–23. Disponível em: <a href="https://www.thenewatlantis.com/publications/why-the-arabic-world-turned-away-from-science">https://www.thenewatlantis.com/publications/why-the-arabic-world-turned-away-from-science</a></p><p>[7] — Joe Boyle. Nigeria’s ‘Taliban’ enigma. BBC, 2009. Disponível em: <a href="http://news.bbc.co.uk/2/hi/africa/8172270.stm">http://news.bbc.co.uk/2/hi/africa/8172270.stm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcbdf97bfe39" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>