Bringing code analysis tools to Jupyter notebooks

Based on a survey of thousands of machine learning practitioners, a new CodeGuru extension addresses common problems, such as code cell execution order, incorrect API calls, and security.

The computational notebook is an interactive, web-based programming interface based on the concept of a lab notebook. Users can describe the computations they’re performing — including diagrams — and embed code in the notebook, and the notebook backend will execute the code, integrating the results into the notebook layout.

Jupyter Notebook is the most popular implementation of computational notebooks, and it has become the tool of choice for data scientists. By September 2018, there were more than 2.5 million public Jupyter notebooks on GitHub, and this number has been growing rapidly.

Related content
In a pilot study, an automated code checker found about 100 possible errors, 80% of which turned out to require correction.

However, using Jupyter Notebook poses several challenges related to code maintenance and machine learning best practices. We recently surveyed 2,669 machine learning (ML) practitioners, and 33% of them mentioned that notebooks get easily cluttered due to the mix of code, documentation, and visualization. Similarly, 23% found silent bugs hard to detect, and 18% agreed that global variables are inconsistently used. Another 15% found reproduction of notebooks to be hard, and 6% had difficulty detecting and remediating security vulnerabilities within notebooks.

We are excited to share our recent launch of the Amazon CodeGuru extension for JupyterLab and SageMaker Studio. The extension seamlessly integrates with JupyterLab and SageMaker Studio, and with a single button click, it can provide users feedback and suggestions for improving their code quality and security. To learn more about how to install and use this extension, check out this user guide.

Static analysis

Traditional software development environments commonly use static-analysis tools to identify and prevent bugs and enforce coding standards, but Jupyter notebooks currently lack such tools. We on the Amazon CodeGuru team, which has developed a portfolio of code analysis tools for Amazon Web Services customers, saw a great opportunity to adapt our existing tools for notebooks and build solutions that best fit this new problem area.

Notebook-Interface.jpg
An example of how the notebook environment can integrate discussion, code, and visualizations.

We presented our initial efforts in a paper published at the 25th International Symposium on Formal Methods in March 2023. The paper reports insights from our survey and from interviews with ML practitioners to understand what specific issues need to be addressed in the notebook context. In the following, we give two examples of how our new technologies can help machine learning experts to be more productive.

Execution order

Code is embedded in computational notebooks in code cells, which can be executed in an arbitrary order and edited on the fly; that is, cells can be added, deleted, or changed after other cells have been executed.

While this flexibility is great for exploring data, it raises problems concerning reproducibility, as cells with shared variables can produce different results when running in different orders.

Jupyter code examples.png
Left: code cells executed in nonlinear order; right: code cells executed in linear order.

Once a code cell is executed, it is assigned an integer number in the square bracket on its left side. This number is called the execution count, and it indicates the cell’s position in the execution order. In the example above, when code cells are executed in nonlinear order, the variable z ends up with the value 6. However, execution count 2 is missing in the notebook file, which can happen for multiple reasons: perhaps the cell was executed and deleted afterwards, or perhaps one of the cells was executed twice. In any case, it would be hard for a second person to reproduce the same result.

Related content
New tool can spot problems — such as overfitting and vanishing gradients — that prevent machine learning models from learning.

To catch problems resulting from out-of-order execution in Jupyter notebooks, we developed a hybrid approach that combines dynamic information capture and static analysis. Our tool collects dynamic information during the execution of notebooks, then converts notebook files with Python code cells into a novel Python representation that models the execution order as well as the code cells as such. Based on this model, we are able to leverage our static-analysis engine for Python and design new static-analysis rules to catch issues in notebooks.

APIs

Another common problem for notebook users is misuse of machine-learning APIs. Popular machine learning libraries such as PyTorch, TensorFlow, and Keras greatly simplify the development of AI systems. However, due to the complexity of the field, the libraries’ high level of abstraction, and the sometimes obscure conventions governing library functions, library users often misuse these APIs and inject faults into their notebooks without even knowing it.

Related content
ICSE paper presents techniques piloted by Amazon Web Services’ Automated Reasoning team.

The code below shows such a misuse. Some layers of a neural network, such as dropout layers, may behave differently during the training and evaluation of the network. PyTorch mandates explicit calls to train() and eval() to denote the start of training and evaluation, respectively. The code example is intended to load a trained model from disk and evaluate it on some test data.

However, it misses the call to eval(), as by default, every model is in the training phase. In this case, some layers will indirectly change the architecture of the network, which would make all prediction unstable; i.e., for the same input, the predictions would be different at different times.

# noncompliant case
model.load_state_dict(torch.load("model.pth"))
predicted = model.evaluate_on(test_data)

# compliant case
model.load_state_dict(torch.load("model.pth"))
model.eval()
predicted = model.evaluate_on(test_data)

Instabilities caused by this bug can have a serious impact. Even when the bug is found (currently, through manual code review) and fixed, the model needs to be retrained. Depending on how large the model is and how late in the development process the bug is found, this could mean a waste of thousands of hours.

The best case would be to detect the bug directly after the developer writes the code. Static analysis can help with this. In our paper, we implemented a set of static-analysis rules that automatically analyze machine learning code in Jupyter notebooks and could detect such bugs with high precision.

In experiments involving a large set of notebook files, our rules found an average of one bug per seven notebooks. This result motivates us to dive deep into bug detection in Jupyter notebooks.

Our survey identified the following issues that notebook users care about:

  • Reproducibility: People often find it difficult to reproduce results when moving notebooks between different environments. Notebook code cells are often executed in nonlinear order, which may be not reproducible. About 14% of the survey participants collaborate on notebooks with others only when models need to be pushed into production; reproducibility is even more crucial for production notebooks.
  • Correctness: People introduce silent correctness bugs without knowing it when using machine learning libraries. Silent bugs affect model outputs but do not cause program crashes, which makes them extremely hard to find. In our survey, 23% of participants confirmed this.
  • Readability: During data exploration, notebooks can easily get messy and hard to read. This hampers maintainability as well as collaboration. In our survey, 32% of participants mentioned that readability is one of the biggest difficulties in using notebooks.
  • Performance: It is time- and memory-consuming to train big models. People want help to make both training and the runtime execution of their code more efficient.
  • Security: In our survey, 34% of participants said that security awareness among ML practitioners is low and that there is a consequent need for security scanning. Because notebooks often rely on external code and data, they can be vulnerable to code injection and data-poisoning attacks (manipulating machine learning models).

These findings pointed us toward the kinds of issues that our new analysis rules should address. During the rule sourcing and specification phase, we asked ML experts for feedback on the usefulness of the rules as well as examples of compliant and noncompliant cases to illustrate the rules. After developing the rules, we invited a group of ML experts to evaluate our tools on real-world notebooks. We used their feedback to improve the accuracy of the rules.

The newly launched Amazon CodeGuru extension for JupyterLab and SageMaker Studio enables the enforcement of code quality and security in computational notebooks to “shift left”, or move earlier in the development process. Users can now detect security vulnerabilities — such as injection flaws, data leaks, weak cryptography, and missing encryption — within notebook cells, along with other common issues that affect the readability, reproducibility, and correctness of the computations performed by notebooks.

Acknowledgements: Martin Schäf, Omer Tripp

Research areas

Related content

US, WA, Bellevue
Have you ever ordered a product on Amazon and when that box with the smile arrived you wondered how it got to you so fast? Have you wondered where it came from and how much it cost Amazon to deliver it to you? If so, the WW Amazon Logistics, Business Analytics team is for you. We manage the delivery of tens of millions of products every week to Amazon’s customers, achieving on-time delivery in a cost-effective manner. We are looking for an enthusiastic, customer obsessed, Sr. Applied Scientist with good analytical skills to help manage projects and operations, implement scheduling solutions, improve metrics, and develop scalable processes and tools. The primary role of an Operations Research Scientist within Amazon is to address business challenges through building a compelling case, and using data to influence change across the organization. This individual will be given responsibility on their first day to own those business challenges and the autonomy to think strategically and make data driven decisions. Decisions and tools made in this role will have significant impact to the customer experience, as it will have a major impact on how the final phase of delivery is done at Amazon. Ideal candidates will be a high potential, strategic and analytic graduate with a PhD in (Operations Research, Statistics, Engineering, and Supply Chain) ready for challenging opportunities in the core of our world class operations space. Great candidates have a history of operations research, and the ability to use data and research to make changes. This role requires robust program management skills and research science skills in order to act on research outcomes. This individual will need to be able to work with a team, but also be comfortable making decisions independently, in what is often times an ambiguous environment. Responsibilities may include: - Develop input and assumptions based preexisting models to estimate the costs and savings opportunities associated with varying levels of network growth and operations - Creating metrics to measure business performance, identify root causes and trends, and prescribe action plans - Managing multiple projects simultaneously - Working with technology teams and product managers to develop new tools and systems to support the growth of the business - Communicating with and supporting various internal stakeholders and external audiences
US, CA, Sunnyvale
Amazon Industrial Robotics is seeking exceptional talent to help develop the next generation of advanced robotics systems that will transform automation at Amazon's scale. We're building revolutionary robotic systems that combine cutting-edge AI, sophisticated control systems, and advanced mechanical design to create adaptable automation solutions capable of working safely alongside humans in dynamic environments. This is a unique opportunity to shape the future of robotics and automation at unprecedented scale, working with world-class teams pushing the boundaries of what's possible in robotic manipulation, locomotion, and human-robot interaction. This role presents an opportunity to shape the future of robotics through innovative applications of deep learning and large language models. We leverage advanced robotics, machine learning, and artificial intelligence to solve complex operational challenges at unprecedented scale. Our fleet of robots operates across hundreds of facilities worldwide, working in sophisticated coordination to fulfill our mission of customer excellence. We are pioneering the development of robotics foundation models that: - Enable unprecedented generalization across diverse tasks - Integrate multi-modal learning capabilities (visual, tactile, linguistic) - Accelerate skill acquisition through demonstration learning - Enhance robotic perception and environmental understanding - Streamline development processes through reusable capabilities The ideal candidate will contribute to research that bridges the gap between theoretical advancement and practical implementation in robotics. You will be part of a team that's revolutionizing how robots learn, adapt, and interact with their environment. Join us in building the next generation of intelligent robotics systems that will transform the future of automation and human-robot collaboration. As an Applied Scientist, you will develop and improve machine learning systems that help robots perceive, reason, and act in real-world environments. You will leverage state-of-the-art models (open source and internal research), evaluate them on representative tasks, and adapt/optimize them to meet robustness, safety, and performance needs. You will invent new algorithms where gaps exist. You’ll collaborate closely with research, controls, hardware, and product-facing teams, and your outputs will be used by downstream teams to further customize and deploy on specific robot embodiments. Key job responsibilities - Leverage state-of-the-art models for targeted tasks, environments, and robot embodiments through fine-tuning and optimization. - Execute rapid, rigorous experimentation with reproducible results and solid engineering practices, closing the gap between sim and real environments. - Build and run capability evaluations/benchmarks to clearly profile performance, generalization, and failure modes. - Contribute to the data and training workflow: collection/curation, dataset quality/provenance, and repeatable training recipes. - Write clean, maintainable, well commented and documented code, contribute to training infrastructure, create tools for model evaluation and testing, and implement necessary APIs - Stay current with latest developments in foundation models and robotics, assist in literature reviews and research documentation, prepare technical reports and presentations, and contribute to research discussions and brainstorming sessions. - Work closely with senior scientists, engineers, and leaders across multiple teams, participate in knowledge sharing, support integration efforts with robotics hardware teams, and help document best practices and methodologies.
US, NY, New York
Advertising at Amazon is growing incredibly fast and we are responsible for defining and delivering a collection of advertising products that drive discovery and sales. Amazon Business Ads is equally growing fast ($XXXMs to $XBs) and owns engineering and science for the AB WW ad experience. We build business-to-business (“B2B”) specific ad solutions distributed across retail and ad systems for shopper and advertiser experiences. Some include new ad placements or widgets, creatives, sourcing techniques, ad campaign management capabilities and much more! We consider unique AB qualities which are differentiated from the consumer experience such as varying shopper role types, purchasing complexities based on business size and industry (eg education vs healthcare), AB specific features (eg business discounts, buying policies to restrict and prefer products), and AB buyer behaviors (eg buying in bulk). We are seeking a scientific leader who can drive innovation in complex problem areas and new business initiatives. The ideal candidate will: Technical & Research Requirements: * Demonstrate fluency in Python, R, Matlab or other statistical languages and familiarity with deep learning frameworks like PyTorch, TensorFlow * Lead end-to-end solution development from research to prototyping and experimentation * Write and deploy significant parts of scientifically novel software solutions into production Leadership & Influence: * Drive team's scientific agenda by proposing new initiatives and securing management buy-in including PM, SDM * Mentor colleagues and contribute to their professional development * Build consensus on large projects and influence decisions across different teams in Ads Key Leadership Principles: * Dive Deep: Uncover non-obvious insights in data * Deliver Results: Create solutions aligned with customer and product needs * Learn and Be Curious: Demonstrate self-driven desire to explore new research areas * Earn Trust: Build relationships with stakeholders through understanding business needs
JP, 13, Tokyo
Are you a Graduate Student interested in machine learning, natural language processing, computer vision, automated reasoning, robotics? We are looking for skilled scientists capable of putting theory into practice through experimentation and invention, leveraging science techniques and implementing systems to work on massive datasets in an effort to tackle never-before-solved problems. A successful candidate will be a self-starter comfortable with ambiguity, strong attention to detail, and the ability to work in a fast-paced, ever-changing environment. As an Applied Scientist, you will own the design and development of end-to-end systems. You’ll have the opportunity to create technical roadmaps, and drive production level projects that will support Amazon Science. You will work closely with Amazon scientists, and other science interns to develop solutions and deploy them into production. The ideal scientist must have the ability to work with diverse groups of people and cross-functional teams to solve complex business problems. Key job responsibilities Amazon Science gives insight into the company’s approach to customer-obsessed scientific innovation. Amazon fundamentally believes that scientific innovation is essential to being the most customer-centric company in the world. It’s the company’s ability to have an impact at scale that allows us to attract some of the brightest minds in artificial intelligence and related fields. Amazon Scientist use our working backwards method to enrich the way we live and work. A day in the life Come teach us a few things, and we’ll teach you a few things as we navigate the most customer-centric company on Earth.
US, NY, New York
At Amazon Selection and Catalog Systems (ASCS), our mission is to power the online buying experience for customers worldwide so they can find, discover, and buy any product they want. We innovate on behalf of our customers to ensure uniqueness and consistency of product identity and to infer relationships between products in Amazon Catalog to drive the selection gateway for the search and browse experiences on the website. We're solving a fundamental AI challenge: establishing product identity and relationships at unprecedented scale. Using Generative AI, Visual Language Models (VLMs), and multimodal reasoning, we determine what makes each product unique and how products relate to one another across Amazon's catalog. The scale is staggering: billions of products, petabytes of multimodal data, millions of sellers, dozens of languages, and infinite product diversity—from electronics to groceries to digital content. The research challenges are immense. GenAI and VLMs hold transformative promise for catalog understanding, but we operate where traditional methods fail: ambiguous problem spaces, incomplete and noisy data, inherent uncertainty, reasoning across both images and textual data, and explaining decisions at scale. Establishing product identities and groupings requires sophisticated models that reason across text, images, and structured data—while maintaining accuracy and trust for high-stakes business decisions affecting millions of customers daily. Amazon's Item and Relationship Platform group is looking for an innovative and customer-focused applied scientist to help us make the world's best product catalog even better. In this role, you will partner with technology and business leaders to build new state-of-the-art algorithms, models, and services to infer product-to-product relationships that matter to our customers. You will pioneer advanced GenAI solutions that power next-generation agentic shopping experiences, working in a collaborative environment where you can experiment with massive data from the world's largest product catalog, tackle problems at the frontier of AI research, rapidly implement and deploy your algorithmic ideas at scale, across millions of customers. Key job responsibilities * Formulate novel research problems at the intersection of GenAI, multimodal learning, and large-scale information retrieval—translating ambiguous business challenges into tractable scientific frameworks * Design and implement leading models leveraging VLMs, foundation models, and agentic architectures to solve product identity, relationship inference, and catalog understanding at billion-product scale * Pioneer explainable AI methodologies that balance model performance with scalability requirements for production systems impacting millions of daily customer decisions * Own end-to-end ML pipelines from research ideation to production deployment—processing petabytes of multimodal data with rigorous evaluation frameworks * Define research roadmaps aligned with business priorities, balancing foundational research with incremental product improvements * Mentor peer scientists and engineers on advanced ML techniques, experimental design, and scientific rigor—building organizational capability in GenAI and multimodal AI * Represent the team in the broader science community—publishing findings, delivering tech talks, and staying at the forefront of GenAI, VLM, and agentic system research
US, MA, N.reading
Amazon Industrial Robotics is seeking exceptional talent to help develop the next generation of advanced robotics systems that will transform automation at Amazon's scale. We're building revolutionary robotic systems that combine cutting-edge AI, sophisticated control systems, and advanced mechanical design to create adaptable automation solutions capable of working safely alongside humans in dynamic environments. This is a unique opportunity to shape the future of robotics and automation at an unprecedented scale, working with world-class teams pushing the boundaries of what's possible in robotic manipulation, locomotion, and human-robot interaction. As an Applied Scientist in Sensing, you will develop innovative and complex sensing systems for our emerging robotic solutions and improve existing on-robot sensing to optimize performance and enhance customer experience. The ideal candidate has demonstrated experience designing and troubleshooting custom sensor systems from the ground up. They enjoy analytical problem solving and possess practical knowledge of robotic design, fabrication, assembly, and rapid prototyping. They thrive in an interdisciplinary environment and have led the development of complex sensing systems. Key job responsibilities - Design and adapt holistic on-robot sensing solutions for ambiguous problems with fluid requirements - Mentor and develop junior scientists and engineers - Work with an interdisciplinary team to execute product designs from concept to production including specification, design, prototyping, validation and testing - Have responsibility for the designs and performance of a sensing system design - Work with the Operations, Manufacturing, Supply Chain and Quality organizations as well as vendors to ensure a fast development and delivery of the sensing concepts to the team - Develop overall safety concept of the sensing platform - Exhibit role model behaviors of applied science best practices, thorough and predictive analysis and cradle to grave ownership
US, CA, San Francisco
Amazon has launched a new research lab in San Francisco to develop foundational capabilities for useful AI agents. We’re enabling practical AI to make our customers more productive, empowered, and fulfilled. In particular, our work combines large language models (LLMs) with reinforcement learning (RL) to solve reasoning, planning, and world modeling in both virtual and physical environments. Our research builds on that of Amazon’s broader AGI organization, which recently introduced Amazon Nova, a new generation of state-of-the-art foundation models (FMs). Our lab is a small, talent-dense team with the resources and scale of Amazon. Each team in the lab has the autonomy to move fast and the long-term commitment to pursue high-risk, high-payoff research. We’re entering an exciting new era where agents can redefine what AI makes possible. We’d love for you to join our lab and build it from the ground up! Key job responsibilities You will be responsible for maintaining our task management system which supports many internal and external stakeholders and ensures we are able to continue adding orders of magnitude more data and reliability.
US, WA, Bellevue
The Amazon Fulfillment Technology (AFT) Science team is seeking an exceptional Applied Scientist with strong operations research and optimization expertise to develop production solutions for one of the most complex systems in the world: Amazon's Fulfillment Network. At AFT Science, we design, build, and deploy optimization, statistics, machine learning, and GenAI/LLM solutions that power production systems running across Amazon Fulfillment Centers worldwide. We solve a wide range of challenges encountered throughout the network, including labor planning and staffing, pick scheduling, stow guidance, and capacity risk management. We are tasked with developing innovative, scalable, and reliable science-driven production solutions that exceed the published state of the art, enabling systems to run frequently (ranging from every few minutes to every few hours per use case) and continuously across our large-scale network. Key job responsibilities As an Applied Scientist, you will collaborate with other scientists, software engineers, product managers, and operations leaders to develop optimization-driven solutions using a variety of tools and observe direct impact on process efficiency and associate experience in the fulfillment network. Key responsibilities include: - Develop understanding and domain knowledge of operational processes, system architecture and functions, and business requirements - Deep dive into data and code to identify opportunities for continuous improvement and/or disruptive new approaches - Develop scalable mathematical models for production systems to derive optimal or near-optimal solutions for existing and new challenges - Create prototypes and simulations for agile experimentation of devised solutions - Advocate for technical solutions with business stakeholders, engineering teams, and senior leadership - Partner with engineers to integrate prototypes into production systems - Design experiments to test new or incremental solutions launched in production and build metrics to track performance A day in the life Amazon offers a full range of benefits that support you and eligible family members, including domestic partners and their children. Benefits can vary by location, the number of regularly scheduled hours you work, length of employment, and job status such as seasonal or temporary employment. The benefits that generally apply to regular, full-time employees include: 1. Medical, Dental, and Vision Coverage 2. Maternity and Parental Leave Options 3. Paid Time Off (PTO) 4. 401(k) Plan If you are not sure that every qualification on the list above describes you exactly, we'd still love to hear from you! At Amazon, we value people with unique backgrounds, experiences, and skillsets. If you’re passionate about this role and want to make an impact on a global scale, please apply! About the team Amazon Fulfillment Technology (AFT) designs, develops, and operates end-to-end fulfillment technology solutions for all Amazon Fulfillment Centers (FCs). We harmonize the physical and virtual worlds so Amazon customers can get what they want, when they want it. The AFT Science team has expertise in operations research, optimization, statistics, machine learning, and GenAI/LLM. We also possess deep domain expertise in operational processes within FCs and their challenges. We prioritize advancements that support AFT tech teams and focus areas rather than specific fields of research or individual business partners. We influence each stage of innovation from inception to deployment, which includes both developing novel solutions and improving existing approaches. Resulting production systems rely on a diverse set of technologies; our teams therefore invest in multiple specialties as the needs of each focus area evolve.
IN, KA, Bengaluru
You will be working with a unique and gifted team developing exciting products for consumers. The team is a multidisciplinary group of engineers and scientists engaged in a fast paced mission to deliver new products. The team faces a challenging task of balancing cost, schedule, and performance requirements. You should be comfortable collaborating in a fast-paced and often uncertain environment, and contributing to innovative solutions, while demonstrating leadership, technical competence, and meticulousness. Your deliverables will include development of thermal solutions, concept design, feature development, product architecture and system validation through to manufacturing release. You will support creative developments through application of analysis and testing of complex electronic assemblies using advanced simulation and experimentation tools and techniques. Key job responsibilities In this role, you will: - Own thermal design for consumer electronics products at the system level, proposing thermal architecture and aligning with functional leads - Perform CFD simulations using tools such as Star-CCM+ or FloEFD to assess thermal feasibility, identify risks, and propose mitigation options - Generate data processing, statistical analysis, and test automation scripts to improve data consistency, insight quality, and team efficiency - Plan and execute thermal validation activities for devices and SoC packages, including test setup definition, data review, and issue tracking - Work closely with cross-functional and cross-geo teams to support product decisions, generate thermal specifications, and align on thermal requirements - Prepare clear summaries and reports on thermal results, risks, and observations for review by cross-functional leads About the team Amazon Lab126 is an inventive research and development company that designs and engineers high-profile consumer electronics. Lab126 began in 2004 as a subsidiary of Amazon.com, Inc., originally creating the best-selling Kindle family of products. Since then, we have produced innovative devices like Fire tablets, Fire TV and Amazon Echo. What will you help us create?
US, WA, Seattle
Employer: Amazon.com Services LLC Position: Economist III (multiple positions available) Location: Seattle, Washington Multiple Positions Available: 1. Partner closely with senior management, business stakeholders, scientist and engineers, and economist leadership to solve key business problems ranging from Amazon Web Services, Kindle, Prime, inventory planning, international retail, third party merchants, search, pricing, labor and employment planning, effective benefits (health, retirement, etc.) and beyond; 2. Build econometric models using our world class data systems and apply approaches from a variety of skillsets - applied macro/time series, applied micro, econometric theory, empirical IO, empirical health, labor, public economics and related fields are all highly valued skillsets at Amazon; 3. Work in a fast moving environment to solve business problems as a member of either a crossfunctional team embedded within a business unit or a central science and economics organization; 4. Develop techniques that apply econometrics to large data sets, address quantitative problems, and contribute to the design of automated systems around the company; and 5. Utilize deep knowledge in time series econometrics, asset pricing, empirical macroeconomics, or the use of micro and panel data to improve and validate traditional aggregative models. (40 hours / week, 8:00am-5:00pm, Salary Range $159,200.00/year to $215,300.00/year) Amazon.com is an Equal Opportunity – Affirmative Action Employer – Minority / Female / Disability / Veteran / Gender Identity / Sexual Orientation