<?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 John Cherian on Medium]]></title>
        <description><![CDATA[Stories by John Cherian on Medium]]></description>
        <link>https://medium.com/@johnche88?source=rss-b0635b952c6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by John Cherian on Medium</title>
            <link>https://medium.com/@johnche88?source=rss-b0635b952c6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:29:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnche88/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[Amazon Bedrock learning series]]></title>
            <link>https://johnche88.medium.com/amazon-bedrock-learning-series-b1455c464fa1?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1455c464fa1</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[aws-opensearch]]></category>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 17:54:36 GMT</pubDate>
            <atom:updated>2024-01-04T17:54:36.076Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you ready to dive into the world of Generative AI and transform your career? With the evolving landscape of technology, the demand for skilled professionals in Generative AI is surging. Amazon Bedrock, a cutting-edge platform, is at the forefront of this revolution, offering an array of tools and features that are shaping the future of AI applications.</p><blockquote>Amazon Bedrock emerges as the preferred choice for enterprises in Generative AI, adeptly addressing key concerns like copyright infringement, regulatory compliance, and data privacy. This makes it an ideal framework for businesses seeking to integrate AI while upholding legal and ethical standards.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2Y6Eq2EUsaKZcL7I" /></figure><h3>Amazon Bedrock: A Gateway to Advanced AI Applications</h3><p>Amazon Bedrock stands out as a fully managed service, designed for building and scaling generative AI applications with ease and efficiency. This platform brings high-performing foundation models from renowned AI companies within your reach, all accessible through a single, streamlined API. Its key features, including model customization using fine-tuning with private data, Retrieval Augmented Generation (RAG) for pertinent responses, and the creation of sophisticated agents for executing complex tasks, set it apart in the AI landscape.</p><p>Supporting a diverse range of models from AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon’s own models like Titan, Amazon Bedrock simplifies secure integration and deployment, liberating users from the complexities of managing infrastructure.</p><h3>A Promising Career Path in Generative AI</h3><p>The career prospects in Generative AI are more promising than ever in 2024. The field is not only intellectually stimulating but also financially rewarding. Here’s a glimpse into the average salary landscape for various roles within this domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D9_LphehLJPSlabY" /></figure><p>With an average salary of approximately $123,448 across these roles, the field of Generative AI is not only intellectually enriching but also financially rewarding. This robust demand and handsome compensation reflect the growing need for skilled professionals in this dynamic field.</p><h3>CloudTechInsights offers Amazon Bedrock Learning Series</h3><figure><img alt="CloudTechInsights offers Amazon Bedrock Learning Series" src="https://cdn-images-1.medium.com/max/176/0*VRhSP7M3aB3xRZI9" /><figcaption><a href="https://www.youtube.com/@CloudTechInsights-hj4pd">YouTube Channel</a></figcaption></figure><p>To help you capitalize on these opportunities CloudTechInsights offers you, the “Amazon Bedrock Learning Series” on <a href="https://www.youtube.com/watch?v=AELMKXw77E8&amp;list=PL0yex2qhae6dWqy_jo0dOu1xtFJ8nxUBd&amp;ab_channel=CloudTechInsights"><strong>YouTube</strong></a><strong>.</strong> Launching in January and February, this series features concise 10–15 minute tutorials that cover foundational topics in Generative AI and Amazon Bedrock. Perfect for both beginners and those seeking to advance their skills, these tutorials are designed to navigate you through the complexities of AI technology.</p><p>This series will explore:</p><ul><li><strong>Knowledge Base: </strong>Empower Amazon Bedrock AI models with extensive information on Vector Database.</li><li><strong>Bedrock Agents: </strong>Learn to build advanced AI agents on Amazon Bedrock for complex tasks.</li><li><strong>LangChain:</strong> Discover how to chain together language models, prompts and tools for enhanced AI applications.</li><li><strong>AI Chatbot:</strong> Develop sophisticated chatbots using powerful Foundational Model from Amazon Bedrock.</li><li><strong>Chain of Thought</strong>: Understand the method for generating coherent and logical responses from Bedrock Foundational AI models using Langchain.</li><li><strong>RAG-Based Bedrock</strong>: Dive into Retrieval Augmented Generation for enriched model responses.</li><li><strong>Fine-tuning Amazon Bedrock Models : </strong>Demonstrate fine tuning the Foundational models offered by Amazon Bedrock.</li></ul><p>And much more! Each episode in the series is a step toward mastering Generative AI, offering insights into building and deploying advanced AI solutions.</p><blockquote>Join Us on This Transformative Journey</blockquote><p>We invite you to join this exciting journey with the Amazon Bedrock Learning Series on <a href="https://www.youtube.com/watch?v=AELMKXw77E8&amp;list=PL0yex2qhae6dWqy_jo0dOu1xtFJ8nxUBd&amp;ab_channel=CloudTechInsights"><strong>YouTube</strong></a><strong>.</strong> Enhance your understanding, develop new skills, and be part of the Generative AI revolution. Subscribe to the series, stay tuned for new releases, and take your first step towards becoming a Generative AI expert.</p><p>Your future in the world of Generative AI starts here. Don’t miss out on this opportunity to elevate your career to new heights with the Amazon Bedrock Learning Series. <a href="https://www.youtube.com/channel/UC38RfE43CYFWRxwO6osTvUw">Subscribe now</a> and be part of the AI transformation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1455c464fa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Bedrock: The AWS Lambda of the Generative AI World]]></title>
            <link>https://johnche88.medium.com/amazon-bedrock-the-aws-lambda-of-the-generative-ai-world-194bbcbca503?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/194bbcbca503</guid>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 20:20:20 GMT</pubDate>
            <atom:updated>2023-10-10T20:20:20.957Z</atom:updated>
            <content:encoded><![CDATA[<p>Amazon Bedrock emerges as a fully managed service, designed to simplify the development and deployment of generative AI applications. Drawing parallels with AWS Lambda’s impact on serverless computing, Bedrock aims to be the go-to platform for generative AI.</p><p><strong>Overview</strong></p><p>Amazon Bedrock offers a range of foundation models (FMs) from prominent AI entities, including AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon. The platform’s design emphasizes ease of use, allowing developers to experiment with various FMs effortlessly. AWS Bedrock takes care of the underlying Generative AI model, operating systems, and dependencies.</p><p>To access these models, an opt-in mechanism is in place. Some models, like those from Anthropic, might require additional request forms. Bedrock’s pricing is transparent, urging users to understand tokenization and the costs associated with each model. For those acquainted with AWS and Boto3, integrating with Bedrock is straightforward.</p><p><strong>Key features, amongst others</strong></p><ul><li>Data Security and Compliance: Amazon Bedrock is built with a strong focus on security and privacy. It boasts HIPAA eligibility and GDPR compliance. Data is encrypted at all times, ensuring that content isn’t used to enhance base models or shared with third-party model providers.</li><li>Easy Model Customization: Users can tailor FMs using a visual interface, eliminating the need for extensive coding. Choose your datasets and tweak hyperparameters if necessary.</li><li>Plug and Play Models: Bedrock promotes effortless integration of various foundation models. The platform facilitates quick model integration and even allows users to craft their own using tools like SageMaker.</li><li>Fully Managed Agents: These agents are equipped to handle intricate business operations, from travel bookings to inventory management, by dynamically interfacing with your organization’s systems and APIs.</li></ul><p><strong>Potential Use Cases</strong></p><ul><li><strong>Chatbots: </strong>Develop chatbots capable of answering queries and disseminating information.</li><li><strong>Text Summarization: </strong>Use Bedrock to condense lengthy texts, be it articles or detailed reports.</li><li><strong>Personalization:</strong> Tailor content to individual preferences, from product suggestions to curated news feeds.</li><li><strong>Image Generation</strong>: Craft unique images, ranging from brand logos to product illustrations.</li><li><strong>Search: </strong>Harness Bedrock to search for specific information, be it products or services.</li></ul><p><strong>Conclusion</strong></p><p>Amazon Bedrock is poised to redefine the landscape of generative AI. With its extensive features, coupled with a commitment to security and adaptability, it stands as a pivotal tool for both developers and enterprises. Whether you’re venturing into generative AI or aiming to amplify your existing applications, Amazon Bedrock lays down a robust foundation.</p><p><em>Note: For more detailed information, you can visit the official </em><a href="https://aws.amazon.com/bedrock/"><em>Amazon Bedrock website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=194bbcbca503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting GPTJ-6B on AWS SageMaker: Unleashing the Power of Large Language Models]]></title>
            <link>https://johnche88.medium.com/hosting-gptj-6b-on-aws-sagemaker-unleashing-the-power-of-large-language-models-2adf5b62d3cb?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2adf5b62d3cb</guid>
            <category><![CDATA[gptj-6b]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[aws-sagemaker]]></category>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Wed, 10 May 2023 20:21:03 GMT</pubDate>
            <atom:updated>2023-05-10T20:21:03.599Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>GPTJ-6B is a powerful transformer model with 6 billion trainable parameters, developed using Ben Wang’s Mesh Transformer JAX. As large language models (LLMs) like GPTJ-6B gain prominence in various industries, hosting them on scalable and efficient platforms like AWS SageMaker becomes crucial. In this blog, we’ll discuss the size of GPTJ-6B, how to host LLMs on AWS SageMaker, and some of the use cases of GPTJ-6B on AWS and in the industry.</p><p><strong>GPTJ-6B Use Cases on AWS and in the Industry</strong></p><p>As a state-of-the-art language model, GPTJ-6B has numerous use cases across industries. Some possible applications include:</p><ol><li>Natural language understanding: GPTJ-6B can be utilized to improve sentiment analysis, document classification, and other natural language understanding tasks, enabling businesses to extract valuable insights from unstructured text data.</li><li>Chatbots and virtual assistants: With GPTJ-6B’s ability to generate coherent and contextually relevant text, it can be employed to create advanced chatbots and virtual assistants that provide more accurate and human-like responses to user queries.</li><li>Content generation: GPTJ-6B can be used for generating high-quality content, such as blog posts, marketing copy, and social media content, enabling businesses to automate and scale their content creation efforts.</li><li>Code completion: GPTJ-6B’s impressive language understanding capabilities can be applied to assist software developers in completing code snippets, detecting syntax errors, and suggesting improvements in real time.</li><li>Education: GPTJ-6B can be employed in educational settings to create personalized learning experiences, generate question-answer pairs for practice, and provide explanations for complex concepts.</li></ol><p>Architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*FRi-NPreUFzWInSw8q3qEA.jpeg" /></figure><p><strong>Resource requirements</strong></p><p>GPT-J is a large language model requiring significant resources for processing. For inference, the model needs approximately 12.1 GB of GPU memory, so an NVIDIA card with at least 16 GB of VRAM and at least 16 GB of CPU RAM is required to load the model.</p><p><strong>Hosting GPTJ-6B on AWS SageMaker</strong></p><p>To host GPTJ-6B on Amazon SageMaker, you can follow these steps as described in a <a href="https://huggingface.co/EleutherAI/gpt-j-6b">Hugging Face blog post</a>:</p><ol><li>Create a model.tar.gz file for the Amazon SageMaker real-time endpoint.</li><li>Deploy the model to Amazon SageMaker using one of the two methods: a. Deploy a model from the Hugging Face Hub directly. b. Deploy a model with model_data stored in Amazon S3.</li></ol><p><strong>Context to prompts</strong></p><p>To perform inference with GPT-J-6B while maintaining conversation history or context, you would need to store the conversation history in a database like DynamoDB. This is necessary because GPT-J, like other large language models, can lose context if not continuously fed with conversation history.</p><p>To retrieve data from DynamoDB and use it as context for GPT-J-6B, you can follow these steps:</p><ol><li>Set up an Amazon DynamoDB table to store the conversation history, as described in my previous response.</li><li>When a new user message arrives, retrieve the conversation history associated with the conversation ID from Amazon DynamoDB using the appropriate SDK for your programming language. For example, in Python, you can use boto3 to query the table and retrieve the conversation history:</li></ol><pre>import boto3<br>from boto3.dynamodb.conditions import Key<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table = dynamodb.Table(&#39;table_name&#39;)<br><br>response = table.query(<br>    KeyConditionExpression=Key(&#39;conversation_id&#39;).eq(your_conversation_id)<br>)<br><br>conversation_history = response[&#39;Items&#39;]</pre><p>3. Process the retrieved data and construct the context string for GPT-J-6B. For example:</p><pre>context = &quot;&quot;<br>for item in conversation_history:<br>    context += f&quot;User: {item[&#39;user_message&#39;]}\nAssistant: {item[&#39;assistant_response&#39;]}\n&quot;</pre><p>4. Feed the context string into GPT-J-6B for a response.</p><pre>from transformers import pipeline<br><br>gptj = pipeline(&quot;text-generation&quot;, model=&quot;EleutherAI/gpt-j-6b&quot;, device=0)<br><br>generated_response = gptj(context + &quot;User: &quot; + new_user_message)[0][&#39;generated_text&#39;]</pre><p>5. Serve the generated response to the user.</p><p><strong>Use private documents as context for GPTJ-6B.</strong></p><p>To answer questions based on enterprise or private documents, a possible approach is to first store all the documents in an Amazon S3 location. Once the documents are stored in Amazon S3, one can use the LlamaIndex library to create an index in a VectorStore index.</p><p>To create the VectorStore index, you can first use the SimpleDirectoryReader class to read the documents from Amazon S3 and load them as data, and then pass the data to the GPTVectorStoreIndex class to create the index.</p><pre>import boto3<br>from llama_index import GPTVectorStoreIndex, SimpleDocumentReader<br><br># Set up AWS credentials.<br>s3 = boto3.client(&#39;s3&#39;)<br><br># Download the file from S3<br>s3.download_file(&#39;BUCKET_NAME&#39;, &#39;FILE_NAME&#39;, &#39;FILE_NAME&#39;)<br><br># Index the document using LlamaIndex<br>reader = SimpleDocumentReader(&#39;FILE_NAME&#39;)<br>index = GPTVectorStoreIndex.from_documents(reader)<br><br><br># Connect to Langchain<br>from langchain.chains.question_answering import load_qa_chain<br><br># set up the parameters<br>model_endpoint = &#39;http://&lt;your_endpoint&gt;.amazonaws.com/model&#39;<br><br>chain = load_qa_chain(model_endpoint, chain_type=&quot;stuff&quot;)<br>chain.run(input_documents=index, question=&quot;prompt or question&quot;)</pre><p><strong>Conclusion</strong></p><p>GPTJ-6B is a powerful and versatile large language model with a wide array of use cases across industries. Hosting this model on AWS SageMaker allows businesses to leverage the power of GPTJ-6B efficiently and at scale. By following the deployment steps mentioned above, you can start exploring the potential applications of GPTJ-6B on AWS and in your industry.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2adf5b62d3cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Runtime for AWS Lambda]]></title>
            <link>https://johnche88.medium.com/spark-runtime-for-aws-lambda-fc9ba889ce7a?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc9ba889ce7a</guid>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 15:14:01 GMT</pubDate>
            <atom:updated>2023-04-14T18:26:31.527Z</atom:updated>
            <content:encoded><![CDATA[<h4>“Outpacing Spark with Pen and Paper: A Data Processing Dilemma.&quot; Have you heard customers claim that manually inserting 10 rows of data is faster than letting Apache Spark work its magic?</h4><blockquote>Do you have the same experience waiting for your small files to process using Apache Spark? Well, guess what? Apache Spark may not be your solution. You see, unlike Pandas, Spark wasn’t designed with small files (under 400 MB) in mind. But don’t worry, we’ll dive into the reasons why and help you figure out the best approach for your data needs.</blockquote><blockquote>Unlike its counterpart, Pandas, Spark was designed with big data loads in mind, and its inner workings — such as JVM startup time, default partitioning, and parallel configuration setups — don’t exactly play nice with smaller files.</blockquote><p>Picture this: <a href="https://github.com/aws-samples/spark-on-aws-lambda"><strong>Spark on AWS Lambda v0.2.0</strong></a>(SoAL Framework), an approach to running Spark in local-mode on AWS Lambda, also known as <strong>Spark runtime for AWS Lambda or SoAL Framework</strong>. It’s a game-changer, with Spark packed into a Docker container while AWS Lambda handles the execution. But wait, there’s more!</p><p>Services like Amazon EMR, AWS Glue, or Amazon EMR Serverless are excellent or meant for big data, but may incur some JVM startup costs for streaming or batch processing smaller files using Apache Spark. Those services, while powerful, can be slow (even slower than Pandas) when dealing with files under 400 MB.</p><p>Enter the container-based strategy, slashing overhead costs and optimizing performance by processing data on a single node. If your heart races at the thought of a cost-effective solution for event-based pipelines with smaller files, look no further than Apache Spark on AWS Lambda. Get ready to explore this innovative alternative and transform your data processing experience!</p><h3><strong>Use cases</strong></h3><p><strong>SoAL Framework v0.2.0</strong> will be a great alternative for these use cases.</p><ul><li>Event-driven processing and payloads from Amazon Managed Kafka and AWS Kinesis triggers can benefit from the optimized resource allocation and reduced latency of this approach. The framework supports loading data into Apache HUDI or Iceberg tables on Amazon S3, offering a streamlined solution for less frequent workloads.</li><li>When dealing with batch processing of small files (under 400MB), Spark on AWS Lambda provides a faster and more cost-effective alternative compared to traditional solutions.</li><li>Running different versions of Spark workloads in parallel is feasible, enabling simultaneous execution and reducing overall processing time.</li></ul><h3>Architecture and patterns</h3><p>Leveraging the <strong>SoAL Framework v0.2.0</strong> functionality, you can execute Spark applications on AWS Lambda comparably to their execution on Amazon EMR and EMR serverless. To achieve this, modify the AWS Lambda Environment variable to reflect the PySpark script location on Amazon S3.</p><p>Upon deploying SoAL Framework v0.2.0, the configuration remains unchanged unless the function is updated or removed. Consequently, Spark logs are integrated into AWS Lambda logs and stored within AWS CloudWatch for seamless log management and monitoring in a technical environment.</p><p>In essence, SoAL Framework v0.2.0 provides a stable, efficient alternative for running Spark applications, with the added benefit of streamlined log storage and accessibility via AWS CloudWatch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*oQOSj-m_3l06CnBjIO0D4g.jpeg" /><figcaption><strong>Spark on AWS Lambda v0.2.0 architecture</strong></figcaption></figure><p>Utilizing the SoAL Framework v0.2.0 architectural pattern allows for the management of multiple workloads concurrently. In this setup, each workload is assigned a distinct AWS Lambda function, which is created and configured according to the specific requirements of the input payload. This approach facilitates efficient resource allocation and workload processing, ensuring optimized performance for diverse workloads in a technical environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*BLsYV3SiZ-ngoFUSR-6CeQ.jpeg" /><figcaption>Multi workload architecture pattern</figcaption></figure><p><strong>Deploy and Test Spark on AWS Lambda v0.2.0 in two steps</strong></p><p><strong>Prerequisites</strong></p><ol><li>Install the awscli and sam cli on the machine. <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">Installation instructions</a></li><li>The AWS EC2 or Cloud9 instance should have a role attached with permission for AWS Cloudformation , Amazon S3, AWS Lambda, AWS CodeBuild to run SAM templates.</li></ol><p>Clone the GitHub repository to local storage and change the directory within the cloned folder to the “Cloudformation” folder.</p><pre>git clone https://github.com/aws-samples/spark-on-aws-lambda.git</pre><p>Run the below AWS SAM template, sam-imagebuilder.yaml, using the command with the –stack-name of your choice. An alternate approach is using the shell script <a href="https://github.com/aws-samples/spark-on-aws-lambda/blob/develop/aws-ecr-repository-push.sh">aws-ecr-repository-push.sh</a>.</p><p>Ensure you provide the FRAMEWORK value HUDI, ICEBERG or DELTA</p><pre>sam deploy --template-file sam-imagebuilder.yaml --stack-name spark-on-lambda-image-builder --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM --resolve-s3 --parameter-overrides &#39;ParameterKey=FRAMEWORK,ParameterValue=HUDI&#39;    </pre><p>The command deploys an AWS CloudFormation stack with the name “spark-on-lambda-image-builder”. The command also runs the AWS CodeBuild project, which builds and pushes the Docker image with the latest tag to AWS ECR.</p><p>After the stack has been successfully deployed, copy the AWS ECR repository URI (i.e., spark-on-lambda-image-builder) that is displayed in the output of the stack.</p><figure><img alt="screenshot of the subset of the output" src="https://cdn-images-1.medium.com/max/1024/1*jvF3nMYgN1tPVBmwsTh1bA.png" /></figure><p>Deploy the AWS SAM Lambda package with the required AWS region, AWS ECR repository, Amazon S3 bucket, and folder information about the spark script to create the AWS Lambda with Spark runtime on AWS Lambda.</p><pre>sam deploy --template-file sam-template.yaml --stack-name spark-on-lambda-stack --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM --resolve-s3 --image-repository &lt;accountno&gt;.dkr.ecr.us-east-1.amazonaws.com/sparkonlambda-spark-on-lambda-image-builder --parameter-overrides &#39;ParameterKey=ScriptBucket,ParameterValue=&lt;Provide the s3 bcucket of the script&gt; ParameterKey=SparkScript,ParameterValue=&lt;provide s3 folder lcoation&gt; ParameterKey=ImageUri,ParameterValue=&lt;accountno&gt;.dkr.ecr.us-east-1.amazonaws.com/sparkonlambda-spark-on-lambda-image-builder:latest&#39;</pre><p>This command creates the AWS Lambda function with the container image from the AWS ECR repository. An output file named packaged-template.yaml is created in the local directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rx_K5rONIBmZ254kPfFtrw.png" /><figcaption>Screenshot on how to change the AWS Lambda environment variable to point the pyspark script on Amazon S3</figcaption></figure><p><strong>Optional step: </strong>To publish the AWS SAM application to the AWS Serverless Application Repository, run the command. This allows SAM template sharing with a GUI interface using the AWS Serverless Application Repository, and other developers can leverage quick deployments in the future.</p><p><em>sam publish — template packaged-template.yaml</em></p><p>The template below will be created in the AWS Serverless Application Repository. You can make it private within the enterprise or public. AWS Lambda can be created for each workload separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRr6faj33AEq5xTOWTIfOA.png" /><figcaption>Published on Serverless Application Repository for enterprise wide or public sharing.</figcaption></figure><p>Upon successful command execution, an AWS Lambda function is created using the Spark Container as its runtime. To test the AWS Lambda functions, utilize the PySpark scripts found in the spark-scripts folder. Example scripts are provided for streaming, batch processing with Apache HUDI, Apache Iceberg, and Apache Delta tables.</p><p><strong>Note :</strong> Please specify <strong>S3a</strong> file path for all the input and output locations, e.g., <strong>S3a: </strong>//bucket/filename.csv</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*sg1QQI2jUbMx1uXh0WN2UA.png" /></figure><p>When AWS Lambda is triggered, the PySpark script is uploaded from the Amazon S3 folder to the container’s local storage and executed within the AWS Lambda Spark container. The script submission to the Spark engine is facilitated using the SPARK-SUBMIT command, ensuring seamless execution within the Spark environment.</p><p>The docker images are also available on Docker hub</p><pre>docker pull johnche88/spark-on-aws-lambda-hudi</pre><pre>docker pull johnche88/spark-on-aws-lambda-iceberg</pre><pre>docker pull johnche88/spark-on-aws-lambda-delta</pre><p>What if we have an initial load of big data?</p><p>Imagine tackling an initial load with substantial data volume. Fear not, as SoAL Framework v0.2.0 employs vanilla Spark for data processing scripts, enabling seamless submission to more powerful engines like AWS EMR for handling the initial load. Once completed, you can transition subsequent loads to SoAL Framework v0.2.0 for optimal resource management and cost-effectiveness. In essence, this flexible approach allows you to harness the best of both worlds, catering to your data processing needs with elegance and efficiency. Alternatively, you can chunk and stream the big from Amazon S3.</p><p><strong>In conclusion</strong>, running Spark in local mode on AWS Lambda using a Docker container offers several advantages, especially when dealing with small files and specific use cases. By reducing overhead, simplifying resource management, and leveraging containerization benefits, Spark can achieve faster execution times. Additionally, the event-driven architecture and automatic scalability of AWS Lambda enable efficient and timely processing of Spark jobs. Ultimately, this approach not only improves performance but also proves to be cost-effective with AWS Lambda’s pay-per-use model, making it a compelling solution for small or infrequent workloads in modern data processing pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc9ba889ce7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What version of Apache Spark would you like to use on AWS?]]></title>
            <link>https://johnche88.medium.com/what-version-of-apache-spark-would-you-like-to-use-on-aws-1522d58bf522?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1522d58bf522</guid>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 18:43:49 GMT</pubDate>
            <atom:updated>2022-09-07T18:48:26.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmdA-LpSTLRum1wmhIr0xw.png" /></figure><p>My First take on Amazon EMR Serverless</p><p>What version of Apache Spark would you like to use on AWS?<br>I faced the same issue at the ice cream shop when I was a child. There are 5 ways to run Spark jobs on AWS. AWS Glue, Amazon EMR-EC2, Amazon EMR on EKS, AWS Fargate and Amazon EMR serverless. Most of the time, it is challenging to choose one over the other or understand the aspects to take into account.</p><p>In terms on easy to work and granular control with then it follows the sequence Amazon EMR on EKS, EMR on EC2 , EMR serverless and then AWS Glue. The Amazon EMR Serverless service handles infrastructure setup, instance type selection, and scaling up and down, allowing the user to concentrate solely on the code. The Amazon EMR Serverless does not include all of the AWS glue wrapper libraries that automate tasks such as bookmarking, performance tuning, database connection, data processing, and data flattening. At the same time, unlike Amazon EMR on EC2, you do not need to worry about infrastructure provisioning or scaling up or down based on the workload. The Amazon EMR Serverless is a new deployment option where the spark code on EMR serverless is open-source and can be migrated to other frameworks such as Amazon EMR on EC2 or EKS as needed. The spark configuration dynamic allocation is enabled so the scaling up and down is taken care behind the scene. The Amazon EMR serverless currently supports only Batch jobs no streaming. The EMR serverless configuration is based on virtual CPU, which means that it is running on a container-based environment that, unlike Amazon EMR on EC2, can slice an EC2 into more sub units called vCPUs.</p><p>The Amazon EMR serverless is ideal for short-running batch jobs, and for longer-running jobs, Amazon EMR on EC2 may be less expensive at times. Amazon EMR serverless is ideal for not-so-big data or borderline big data because of the cost savings and potential high data growth rate. Keep in mind that there is an overhead cost for warming up the cluster and then submitting the job, so for small data sets, Pandas may outperform Spark. You can use the pre-initialized capacity feature to have some workers ready before submitting the job. The EMR serverless currently runs Spark and HIVE, with Presto in the works, so it has fewer options than EMR on EC2. It works with Apache HUDI and Apache Iceberg at a lower cost.</p><p><strong>Few highlights</strong></p><ul><li>The Amazon Redshift connection must be manually configured. Except for redshift-jdbc.jar, which must be downloaded and placed on the Amazon S3 folder, some of the jar files are available locally to the Amazon EMR serverless server.</li><li>Adding additional python libraries to the EMR required packaging them in a python virtual environment, zipping them, and pointing spark submit to the python libraries. While packaging, keep in mind to use AWS Cloud 9 with Amazon-Linux -2.</li><li>AWS Lakeformation is not support by the Amazon EMR Serverless. If this is a main requirement then avoid EMR serverless.</li><li>If Airflow is used to orchestrate Spark jobs, there are only a few operators available in <a href="https://github.com/aws-samples/emr-serverless-samples">Github</a>, and it is still evolving. Python operator can be used in conjunction with AWS BOTO3 SDKs to create alternative DAGs.</li><li>Sometime the warm-pool workers or pre-initialized capacity are not fast on submitting the job and there is a 2–3 minutes delays to see the results.</li></ul><p>Below is an example of an Airflow Dag submitting a job on Amazon EMR serverless.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e5fbcdbeff7a2e7f1557b6d58df1b2c/href">https://medium.com/media/1e5fbcdbeff7a2e7f1557b6d58df1b2c/href</a></iframe><p>Overall, my experience with Amazon EMR serverless has been great. I would suggest using EMR serverless for batch jobs that do not require integration with AWS Lakeformation. If additional features are required in the future and are not available on Amazon EMR Serverless, the code can be easily migrated to Amazon EMR on EC2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1522d58bf522" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Benchmarking for Pandas On AWS lambda for CSV files]]></title>
            <link>https://johnche88.medium.com/pandas-with-aws-lambda-benchmarking-for-csv-files-a6d5cf252ce4?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6d5cf252ce4</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-wrangler]]></category>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 20:22:44 GMT</pubDate>
            <atom:updated>2022-04-28T20:13:22.559Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we want to explore the data size limit for CSV format files on AWS S3 for the combination of AWS Wrangler and Pandas on AWS Lambda. The data set used for the benchmarking was downloaded from the geographical Society. The results of the performance test may vary based on the different factors like dataset, datatype, class methods, format of the data, data type composition, Read/Write methods, AWS Lambda Cold Start, coding practices, and many more. The files of various sizes are created for the performance test using pandas in the AWS S3 location. The files are uploaded to an AWS S3 location and the data types include integer, object, and string. I see this blog as a collaborative space for anyone using Pandas with AWS Lambda and sharing their experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*fuGO7LjBiAm1ziFkMuOdKQ.png" /><figcaption><a href="https://images.app.goo.gl/r5z2GoHCwK6DAu5o6">source</a></figcaption></figure><p><strong>Test Scenarios</strong></p><p><strong>Scenario 1-Read and Write CSV format (no compression)</strong></p><p>The first test is to check if Pandas and AWS Lambda can handle different data sizes for simple read and write operations. The AWS lambda code uses the Pandas and AWS Wrangler libraries for this test. File sizes from 50 MB to 2 GB per payload are used in this test. The AWS lambda code reads the csv file from the AWS S3 location using the read_csv method and writes it using the write_csv method to the AWS S3 location. The metrics monitored in this test are</p><ul><li>Data Size</li><li>Data format (csv)</li><li>Duration</li><li>Max Memory Used</li><li>Pandas in memory usage</li><li>methods to read wrangler s3.read_csv and s3.write_csv</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*CQpIWVg8qxiIR7zDqTT4tQ.png" /></figure><p><strong>Scenario 2 : Read and write Compressed CSV file</strong></p><p>In this performance test, my focus is to see if there are any other methods to load files above 1.2 GB. One other approach is to compress the file before reading. There are different compression algorithm for csv format and zip algorithm is the compression algorithm used in the experiment. I assumed that files under 1.2GB would work well with or without compression. The compressed CSV file makes the I/O operations faster and slightly better performance, but the pandas in memory have to serialize and decompress the data in order to convert it to a pandas data frame. The 2GB file was compressed to a 300MB file and ran the test on the same framework. The AWS lambda threw an out of memory issue. Breaking the big file into smaller chunks is an option before the pandas read, but the use cases with aggregation requirements may not fit this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*AmZkmJyeB9irBvlLtNKRFA.png" /></figure><p><strong>Conclusion</strong></p><p>This performance benchmarking is applicable only on Pandas on AWS Lambda approach. The results may vary based on other factors used. These are not comprehensive test cases for performance and results may vary based on different factors used. This experiment is conducted to get an approximation of the CSV file data size threshold for Pandas on AWS Lambda using AWS S3 as the source. <em>The payload size from S3 to AWS Lambda differs from that of the event payload size to AWS Lambda</em>.</p><p>The <strong>Pandas with AWS Lambda</strong> are best for use cases with 100 KB to 1.2GB <strong>per payload</strong>, and the performance is rarely a concern. Anything above 1.2 GB requires an in-memory capacity of greater than 10 GB or in other words AWS Lambda is limited to10GB memory. The AWS Lambda was not intended to be a heavy data processing engine for long running tasks. During the test, I noticed that the csv file size on AWS S3 is smaller than the in-memory Pandas size, so AWS S3 csv file size will not correlate with 10 GB memory in AWS Lambda. The compression has an effect on the I/O cost in AWS Lambda and it is faster than the uncompressed data. For better performance, other compression algorithm should be used. The majority of use cases at enterprise level is under 1 GB per payload, and for anything more than 1.2 GB, there are other options like Pandas chunking, Dask, and Spark to handle such workloads. The AWS lambda has an option to run concurrently(scale out)with a payload size of under 1.2 GB where the order is not critical. Carefully choosing the framework will reduce the Cost of Infrastructure. This will be an evolving blog, will update as I observe other scenarios and use cases. Please feel free to contribute or share you experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6d5cf252ce4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running data processing containers on AWS Lambda]]></title>
            <link>https://johnche88.medium.com/running-data-processing-containers-on-aws-lambda-9c5d2f2222e6?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5d2f2222e6</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Fri, 15 Apr 2022 19:38:30 GMT</pubDate>
            <atom:updated>2022-05-09T01:14:49.960Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS Lambda supports Docker Container as a Function(CaaF). This adds other dimensions to AWS Lambda, portability, ,dependency handling, and environment setup to the serverless architecture. The CaaF supports use cases where standard environment setup is required, portability, and handling unsupported languages like PHP and hybrid cloud environments. There exists a trend where AWS Lambda is used for data processing and loading when the load duration is no longer than 15 min. Now what is trending is that some of the Apache Spark (not all) use cases are being converted to AWS Lambda cost optimized data processing pipelines. Some use cases have seen more than a 50% reduction in AWS Cloud costs.</p><p>What is Big data?</p><p>“Big data” is defined as data that contains greater variety, arriving in increasing volumes and with more velocity. Big data is typically a dataset that cannot be processed using traditional processing engines. The big data concept has evolved in the last 3 decades. In the 90s, the 1 GB payload was considered big data, but today TBs and PBs are considered big data. The concept and definition of big data are evolving. Most of the enterprise use cases may not have all the three V’s and may not require heavy big data frameworks like Spark and MPPs. The key determining factors are whether the data is big, of course, the size of the data, ,annual/monthly growth rate of data, and the frequency of data. Some low frequency and under 10 GB payload use cases are dealt with less expensive AWS resources like AWS lambda, AWS ECS container options, and simple AWS EC2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKOMzfR_cmQmIlOv_nb5Fg.png" /></figure><p><strong>Bigger data use cases</strong></p><p>Recently, the AWS Lambda team added 10 GB of ephemeral storage to AWS Lambda, which makes it capable of handling bigger datasets and files. With existing features like 10 GB of memory, concurrency, asynchronous invocations, and a 15-minute soft limit for timeouts, it overlaps into big data processing territory with Apache Spark. The concurrency feature in AWS Lambda makes the above mentioned feature applicable per payload, i.e. if the big data can be handled into small chunks under 10 GB. Some semi-big data use case scenarios can now be handled in AWS Lambda by combining Pandas, AWS BOTO3, and AWS Wrangler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*VUZJmIfKkARcGDztc6Ki-g.png" /></figure><p><strong>AWS Lambda Container approach</strong></p><p>In the CaaF approach, the AWS also provides the customer with ready made base images which are constantly patched and updated so that it is quicker to add code to the image. The Docker containers can be locally developed and tested before deployment to AWS ECR. The containers are portable between AWS resources and hybrid cloud platforms.</p><p><strong>Steps for deploying container in Lambda</strong></p><ol><li>Design docker file/image with AWS base image, dependencies and AWS Lambda code</li><li>Build, test, deploy the container to AWS ECR</li><li>Create AWS Lambda function with live container</li></ol><p><strong>Prerequisites</strong></p><p>Docker installed in local machine<br>AWS Account and Access<br>Prior knowledge of Pandas and AWS Wrangler</p><p><strong>Design of docker image</strong></p><p>Build a docker file using the AWS image. Add requirement.txt files with all the required libraries for the data processing logic. Then add the lambda_code.py with the data processing python logic.</p><pre>#base image from AWS<br>FROM public.ecr.aws/lambda/python:3.8</pre><pre>#pull lambda code in<br>COPY lambda_code.py .</pre><pre>#add the pandas, wrangler dependencies<br>COPY requirements.txt .</pre><pre>#install all the dependencies<br>RUN pip install -r requirements.txt</pre><pre>#Run the command when triggered<br>CMD [ &quot;lambda_code.run&quot; ]</pre><p><strong>Build, test, deploy the container to AWS ECR</strong></p><p>Browse to the folder where all the docker related files are created</p><pre>docker build -t data-processing-lambda .</pre><p>Run the docker image</p><pre>docker run -p 9000:8080 data-processing-lambda</pre><p>Authenticate the docker CLI with AWS ECR</p><pre>aws ecr get-login-password --region <em>us-east-1</em> | docker login --username AWS --password-stdin <em>&lt;account&gt;</em>.dkr.ecr.<em>us-east-1</em>.amazonaws.com</pre><p>Create the AWS ECR repository</p><pre>aws ecr create-repository --repository-name Data-processing-lambda --image-scanning-configuration scanOnPush=true --image-tag-mutability MUTABLE</pre><p>Tag the image and push it to AWS ECR repo</p><pre># tagging the image before the AWS ECR push</pre><pre>docker tag  Data-processing-lambda:latest <em>123456789012</em>.dkr.ecr.<em>us-east-1</em>.amazonaws.com/Data-processing-lambda:latest </pre><pre># AWS ECR push to repository</pre><pre>docker push <em>&lt;account&gt;</em>.dkr.ecr.<em>us-east-1</em>.amazonaws.com/Data-processing-lambda:latest</pre><p><strong>Create AWS Lambda function with live container</strong></p><p>Now the image is in the AWS ECR repository, the next step is create a lambda function that can pull the image from AWS ECR and be triggered.</p><p>Set the environment variable under AWS Lambda configuration. These environment variables are captured by the python OS library within the python script and applied in the read/write logic.</p><p>Run and test if the CSV file is generated in the target location</p><p><strong>Github<br></strong>All the code mentioned in the blog at my <a href="https://github.com/JohnChe88/AWSSAM-Lambda/tree/master/PandasonDocker">github page</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5d2f2222e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS SAM(Serverless Application Model)is an open source framework that enables AWS users to build…]]></title>
            <link>https://johnche88.medium.com/aws-sam-serverless-application-model-is-an-open-source-framework-that-enables-aws-users-to-build-425bf6a77423?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/425bf6a77423</guid>
            <category><![CDATA[aws-lambda-functions]]></category>
            <category><![CDATA[aws-sam]]></category>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 02:49:44 GMT</pubDate>
            <atom:updated>2022-04-13T02:59:38.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2S3bZYAcIpp_HLq95PrFQA.png" /></figure><p>AWS SAM(Serverless Application Model)is an open source framework that enables AWS users to build, test locally and deploy AWS Lambda to the Cloud. There are many tools to simplify the development of Serverless functions: cross-vendor <a href="https://www.serverless.com/">Serverless framework</a>, AWS-specific <a href="https://aws.amazon.com/serverless/sam/">Serverless Application Model (SAM)</a>, and others. The AWS SAM is widely used in AWS cloud. It can organize related components configurations and deploy all the connected resources together as an entity. It uses cloud formation behind the scenes for building resources but fewer lines of code and some implicit permission handling. For regular deployment of AWS lambda using AWS Cloudformation requires AWS S3 folder for the code artifacts but deployment via AWS SAM cli it handles the folder on its own.</p><p>It provides an environment where you can test AWS Lambda locally and fix bugs, saving cost and time. It integrates well with AWS Code deploy, AWS Codebuild and AWS Codepipeline. The instructions for the build and deploy are provided in the form YAML file.</p><p><strong>Prerequisites</strong></p><p>Install the AWS CLI and AWS SAM on your operating system.<br> <strong>Windows </strong>— install using MSI installer l<a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-windows.html">ink</a> <br> <strong>Linux-</strong> Download the Zip file and follow the <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-linux.html">link</a><br> <strong>Mac</strong>- install using Brew and follow the <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-mac.html">link</a><br>All the code for this article is in the repo <a href="https://github.com/JohnChe88/AWSSAM-Lambda/tree/master/SAM-AWSLambda-test">Code reference </a><br>Setup the Access key using AWS Configure</p><h3><strong>Build, Test and Deploy</strong></h3><ol><li>Create SAM template</li><li>Build</li><li>Test</li><li>Deploy</li></ol><p><strong>Create SAM template</strong></p><p>The SAM template is a YAML file similar to the AWS Cloudformation template. The SAM template file is template.yaml in the github repository mentioned before. With few lines of configuration, we can define the event trigger , AWS lambda code and destination of AWS Lambda. Below template, has the information to build AWS lambda function with an S3 trigger. The transform tag in the template.yaml file indicates AWS SAM template. Some of the IAM role is defined implicitly for S3 to trigger AWS Lambda. There are options define Lambda configuration parameters and settings in SAM template like Ephemeral storage, Memory Size, Timeout and Tracing etc.</p><pre>AWSTemplateFormatVersion: &#39;2016-10-31&#39;<br>Transform: AWS::Serverless-2016-10-31<br>Description: <br>  AWS Lambda SAM Build, deploy , test locally</pre><pre>Resources:<br>  AWSSAMLambdaFunction:<br>    Type: AWS::Serverless::Function <br>    Properties:<br>      CodeUri: LambdaCode/<br>      Handler: app.lambda_handler<br>      Runtime: python3.9<br>      Timeout: 75<br>      <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-functionname">FunctionName</a>: AWSSAMtest<br>      <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-memorysize">MemorySize</a>:512<br>      Events:<br>        CreateFileEvent:<br>          Type: S3<br>          Properties:<br>            Bucket: !Ref SrcBucket<br>            Events: s3:ObjectCreated:*</pre><pre>SrcBucket:<br>        Type: AWS::S3::Bucket</pre><p><strong>Build</strong></p><p>Create a local python project using any IDE. The python project folder should contain below files for SAM to work</p><p>* lambda.py — Main python code for the business logic, <br>* requirements.txt- contains all the required libraries. It is formed as subfolder in the AWS lambda console<br>* event.json — Sample event for the corresponding trigger event. It simulates real world scenarios like S3 event, MSK Kafka trigger<br>* template.yaml -AWS Cloudformation instructions to build the AWS lambda, Role and other triggers if required.</p><p><strong>Test</strong></p><p>To test AWS lambda locally, you can either invoke lambda with the event-generated command or enable HTTP trigger for Lambda invoke and run automated test.</p><p><strong>Test Event generation and invoke by SAM</strong></p><p>You can generate sample events for local testing using the SAM command line. The command <em>sam local generate-event</em> followed by the AWS resource name and parameters creates the event payload.</p><p>The command <em>sam local invoke</em> will invoke a local AWS lambda script and quits after the invocation is completed. Below command simulates a PUT event in the S3 bucket and simulates the invocation of AWS lambda on cloud locally</p><pre># using the SAM command you can generate certain AWS resource event locally and test Lambda locally</pre><pre>sam local generate-event s3 [put/delete] --help</pre><pre># Below command automatically generate the put and delete event locally and pass it to Lambda.py code for testing purposes.</pre><pre>sam local generate-event s3 [put/delete] --bucket &lt;bucketname&gt; --key &lt;prefixname&gt; | sam local invoke -e - &lt;sample SAM function lambda.py &gt;</pre><p><strong>Test AWS lambda using URL option</strong></p><p>This approach allows invoking the local Lambda function and exposing the code using a URL. Once the Lambda is available as a URL then automated test cases can be applied before any code change and deployment . Using the boto3 AWS SDK you can automate the testing by providing different testing scenarios using the URL.</p><pre># browse to the folder and start the Lambda<br>sam local start-lambda [OPTIONS]</pre><pre>#publish the local lambda app to HTTP url<br>aws lambda invoke --function-name &quot;SAMTestApp&quot; --endpoint-url &quot;http://127.0.0.1:3001&quot; --no-verify-ssl out.txt</pre><p><strong>Deploy</strong></p><p>Once the build and local testing is complete, the next step is to deploy lambda to AWS cloud. Using the command line interface, browse to the project folder and run the below command. In the deployment, SAM transforms and expands the SAM syntax into AWS CloudFormation syntax, enabling you to build serverless applications quicker</p><pre>$ sam build</pre><p>Above command builds the application and takes care of the dependencies to the related project. You will notice a new folder and build.toml created under the python project folder with details to the build and deploy AWS Lambda</p><pre>$ sam deploy <br># or<br>$ sam-deploy --guided</pre><p>Above command deploy will ask for some questions and confirmation before creating resources using cloud formation and continue with deployment. This process will take a few minutes based on the resource configuration. The deploy command locates all the required files like template.yaml in the current project folder. For more <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-deploy.html">details</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Tj41QIbN7uydv_ZTuO8cw.jpeg" /></figure><p>Check the AWS Cloudformation console to ensure all the components are build and successfully created. Also check the AWS lambda console to ensure that the function is created and IAM role for the lambda is created.</p><p>Using AWS SAM, we can build, test and deploy from a local Python IDE. It can be used to organize related components, share configuration such as memory and timeouts between resources, and deploy all related resources entity. It enables quicker development, dependent library installation and cost optimized route to develop AWS lambda script.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=425bf6a77423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster Java UDF in Pyspark]]></title>
            <link>https://johnche88.medium.com/faster-java-udf-in-pyspark-f330421dad9e?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f330421dad9e</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[udf]]></category>
            <category><![CDATA[java-udf]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Fri, 11 Feb 2022 20:21:44 GMT</pubDate>
            <atom:updated>2022-02-11T20:21:44.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Using UDFs (User Defined Functions) in spark is probably the last resort for building column-based data processing logic. The Spark UDF is an expensive operation and is used only to extend or fill in missing functionality of Spark methods or libraries or frameworks that do not have a Python wrapper. The UDF typically is a black box for Spark Catalyst optimizers, so when forming the execution plan the logic inside UDF is not considered.</p><p>The UDF developed in python acts as an outsider to spark JVM and spin out as a separate python process. This process creates unnecessary overheard and SerDe operations, limiting the performance of pyspark. For this reason, we need Java UDFs for faster processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjmoO54CK43-j6f6zAZdmQ.png" /></figure><p><strong>High level Steps</strong></p><ol><li>Create UDF in Java</li><li>Package Java UDF Class into a uber jar .jar file</li><li>Move jar to yspark application env</li><li>Import Java UDF and register as UDF</li></ol><p><strong>Step 1 : Create UDF in Java</strong></p><p>Using a Java IDE or notepad, create Java UDF. Use the library <em>org.apache.spark.sql.api.java.UDF</em> to extend the java class to run operations on Spark dataframe for <a href="https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/sql/api/java/package-summary.html">more info.</a> The UDF library helps java execute queries on spark dataframe.</p><pre>//Java Class for simple adding constant number to the input</pre><pre><em>package com.example.jche88;</em></pre><pre><em>import org.apache.spark.sql.api.java.UDF1;<br><br>public class Add implements UDF1&lt;Int, Int&gt; {<br>  <br>  public Long call(Int num) throws Exception <br>      {<br>        return (num +100);<br>      }<br>    }</em></pre><p><strong>Step 2: Package UDF in jar file</strong></p><p>Packaging and creation of jar files is done using Maven, a java build tool. Maven is a build automation tool used primarily for Java projects. For Maven to work, it requires pom.xml, where all the dependencies and libraries are mentioned in the XML format . Setup a maven pom.xml file in the format below or use a template from the Maven site. All the class dependencies and libraries mentioned in the pom.xml file will be packaged into the jar file. There are options in pom.xml to mention the source &amp; target version of compiler, dependent libraries, name of the jar file and name of the project.</p><pre><em>-- pom.xml files used in the project. Feel free to create your own</em></pre><pre><em>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;</em><a href="http://maven.apache.org/POM/4.0.0"><em>http://maven.apache.org/POM/4.0.0</em></a><em>&quot;<br>         xmlns:xsi=&quot;</em><a href="http://www.w3.org/2001/XMLSchema-instance"><em>http://www.w3.org/2001/XMLSchema-instance</em></a><em>&quot;<br>         xsi:schemaLocation=&quot;</em><a href="http://maven.apache.org/POM/4.0.0"><em>http://maven.apache.org/POM/4.0.0</em></a><em> </em><a href="http://maven.apache.org/xsd/maven-4.0.0.xsd"><em>http://maven.apache.org/xsd/maven-4.0.0.xsd</em></a><em>&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;</em></pre><pre><em>&lt;groupId&gt;com.example.jche88&lt;/groupId&gt;<br>    &lt;artifactId&gt;JavaUDFProject&lt;/artifactId&gt;<br>    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;</em></pre><pre><em>&lt;properties&gt;<br>        &lt;maven.compiler.source&gt;1.8&lt;/maven.compiler.source&gt;<br>        &lt;maven.compiler.target&gt;1.8&lt;/maven.compiler.target&gt;<br>    &lt;/properties&gt;</em></pre><pre><em>&lt;build&gt;<br>        &lt;finalName&gt;JavaUDFjarfile&lt;/finalName&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>                &lt;configuration&gt;<br>                    &lt;source&gt;1.8&lt;/source&gt;<br>                    &lt;target&gt;1.8&lt;/target&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;</em></pre><pre><em>&lt;dependencies&gt;</em></pre><pre><em>&lt;dependency&gt;<br>   &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;<br>   &lt;artifactId&gt;spark-sql_2.11&lt;/artifactId&gt;<br>   &lt;version&gt;2.2.0&lt;/version&gt;<br>  &lt;/dependency&gt;<br>  <br>    &lt;/dependencies&gt;</em></pre><pre><em>&lt;/project&gt;</em></pre><p>Install Maven on your machine and set the environmental PATH accordingly. Once all the prerequisites are complete, use the command prompt and browse to the folder where pom.xml is present and run the below command. Below command will use the pom.xml file to download the required libraries and dependencies and package into one big jar file.</p><p><em>Suggestion- Use maven commands instead of IDE jar creation route.</em></p><pre><em>mvn clean install</em></pre><p>The uber jar a.k.a fat jar file will be created in the location mentioned in the jar output location. This uber jar file will have all the dependent libraries to be executable in a different environment.</p><p><strong>Step 3: Move jar file local to pyspark application</strong></p><p>Move the jar to the same server where the Pyspark program is running. The target environment or serve can be docker container, AWS Glue , Databricks or Standalone pyspark environment. Jar file is independent and only required environment java to execute the classes inside it. Ensure all the permission are set once the file is copied.</p><p><strong>Step 4: Import jar into pyspark application</strong></p><p>In order to use the jar file and classes inside it, it should be imported into the pyspark enviroment. This can be done in three ways,</p><ol><li><strong>Cluster level-</strong> updating the spark config file.</li><li><strong>Application level</strong>- using config option while creating spark session using <em>spark.jars</em></li></ol><pre><em>spark = SparkSession.builder.master(&quot;local[1]&quot;) \<br>       .config(&#39;spark.jars&#39;, &quot;/home/johnche88/JavaUDFProject.jar&quot;)\<br>       .appName(&#39;JavaUDFApp&#39;) \<br>       .getOrCreate()</em></pre><p><strong>3. Spark-Submit level</strong> -The jars can be imported into the pyspark application by setting - -jar option while submitting the spark job</p><pre><em>spark-submit --jar /home/johnche/JavaUDFProject.jar Pyspark_app.py</em></pre><p>Some of the cloud managed services applications, like AWS glue, you can use the path to set a jar in the project details or set it at application level. For others, you can use it at the Spark Submit level or Sparkconfig file (cluster level).</p><pre># Spark code in python</pre><pre><em>from pyspark.sql.types import IntegerType,LongType<br>import pyspark.sql.functions as F<br>from pyspark.sql import SparkSession</em></pre><pre><em>spark = SparkSession.builder.master(&quot;local[1]&quot;) \<br>       .config(&#39;spark.jars&#39;, &quot;/home/johnche88/JavaUDFProject.jar&quot;)\<br>       .appName(&#39;JavaUDFApp&#39;) \<br>       .getOrCreate()</em></pre><p>Register the java function as UDF using the Sparksession method called registerJavaFunction <a href="https://spark.apache.org/docs/2.3.0/api/python/pyspark.sql.html">info</a>.</p><pre>spark.udf.registerJavaFunction(&quot;add&quot;, &quot;com.example.jche88&quot;)</pre><p>Once the registration is complete, try the function on a dummy dataframe</p><pre><em>import pyspark.sql.functions as F</em></pre><pre><em>df = spark.createDataFrame([<br>    (35, &quot;john&quot;),<br>    (40, &quot;joe&quot;),<br>    (26, &quot;Sam&quot;),],<br>    [&quot;age&quot;, &quot;Name&quot;])</em></pre><pre><em>df.withColumn(&quot;age&quot;, F.expr(&quot;add(age)&quot;)).show()</em></pre><p>You will notice and significant improvement in the UDF performance after the conversion to Java UDF.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f330421dad9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing SerDe Modules in Python]]></title>
            <link>https://johnche88.medium.com/comparing-serde-modules-in-python-1455e6713d4d?source=rss-b0635b952c6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1455e6713d4d</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[pickles]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[John Cherian]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 20:50:28 GMT</pubDate>
            <atom:updated>2021-11-11T20:50:28.300Z</atom:updated>
            <content:encoded><![CDATA[<p>SerDe(serialization and deserialization) is a process in the programming world where convert object into byte stream format, so that reusability of the object in the same or across different script or environment. Different python frameworks like pyspark used SerDe to convert the dataframe partition into a serialized format to distribute across nodes.</p><p><strong>Python serialization</strong></p><p>The python serialization libraries are used to conduct serDe operations on Python objects to convert into byte format. These libraries are used to serialize simple data structures like arrays, lists, dictionaries to complex class objects, Machine learning models. For simple use cases, other formats like JSON or YAML are used but to save a complex or long-running object(like ML models) pickling is useful.</p><p><strong>Why Serialization</strong></p><ul><li><em>Object persistence</em> — storing the object’s state in a permanent persistence mechanism such as a database or blob storage. The persisted file can be used in another python script or transferred to another location vis TCP. The state of the object is preserved in the .pickle file.</li><li><em>Preserve State</em> -Serialization allows the developer to save the state of an object and recreate it as needed.</li><li><em>Remote Object access</em>- Serialized objects can be referred by another program in a remote location</li><li><em>Distributed data processing</em> — Data partitions in serialized format can be spread across nodes to parallelly process the data.</li></ul><pre>#Pickling process</pre><pre>import pickle</pre><pre>values=[1,2,3,4,5,65]</pre><pre>with open(&#39;values.pickle&#39;, &#39;wb&#39;) as fOps:<br>    pickle.dump(values, fOps) </pre><figure><img alt="Preserving the State of Python Object at a point in time" src="https://cdn-images-1.medium.com/max/1024/0*JZ2u1Y7OgRVgy-uK" /><figcaption>Photo by <a href="https://unsplash.com/@allwithzest?utm_source=medium&amp;utm_medium=referral">Reka Biro-Horvath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Unpickling</strong></p><p>Unpickling is the process of loading any pickled file into any python object and making it reusable for the same or different script. There are a few good use cases where the machine learning model is pickled after training in order to avoid retraining with the same data set. Later on, the Pickled ML models are used for prediction in a REST API.</p><pre># deserialization process</pre><pre>import pickle</pre><pre># Load data <br>with open(&#39;values.pickle&#39;, &#39;rb&#39;) as fOps:<br>    unserialized_values = pickle.load(fOps)</pre><p><strong>A few Python Serializers</strong></p><p>In python, there are three commonly used serializers.</p><ol><li>Pickle Serializer</li><li>Marshal Serializer</li><li>JSON serializer</li></ol><p><strong>Marshal Module</strong></p><p>Marshal serializer is the primitive serializer but it can only convert some python objects. It converts the state of the object and codebase into a byte array or remote object format. The serialization is a subset of a process within marshaling and marshaling add the code base +data type info to the serialized object. Typical use cases are remote method call from another network.</p><p><strong>Pickle Module</strong></p><p>The Pickle module converts the python object to byte code. Unlike marshal, the pickle is used to object sharing and transfer. The Pickle model made the conversion even faster compared to the marshal module. The Pickling is used in multiprocessing libraries in python to distribute objects on different processors in parallel. Keep in mind byte code is not human readable, so use pickle from a trusted source.</p><p><strong>JSON Module</strong></p><p>The JSON format is text-like and human-readable format thereby making it ais a lightweight format for data- interchange therefore much faster than Pickle. The JSON serialization is meant for objects without schema requirements and there are limitations to the type of python objects it can serialize.</p><p><strong>Compression</strong></p><p>Compression of any serialization format will reduce the time to write the file which increases the speed of serialization and faster transfer across networks.</p><p><strong>Conclusion</strong></p><p>Loading any serialized formats from untrusted sources in Pickle and Marshal is a concern of security. Based on the security concerns, the JSON format is preferred over pickled values as it is fast enough, human-readable, reduces cause security issues, and other programming languages friendly. Compared to JSON, the pickle is slow, insecure, and used in Python only. The main reason pickle is used is to serialize arbitrary Python objects, whereas both JSON have serialization limitations on the type of data. I would like to hear other comments and concerns from the readers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1455e6713d4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>