Showing posts with label OCI. Show all posts
Showing posts with label OCI. Show all posts

Monday, December 18, 2023

Deploy LangChain applications as OCI model deployments

Are you looking for a fast and easy way to deploy your LangChain applications built with large language models (LLMs)? Oracle Accelerated Data Science (ADS) v2.9.1 adds a new feature to deploy serializable LangChain application as REST API on Oracle Cloud Infrastructure (OCI) Data Science Model Deployment. With ADS software developer kits (SDKs), you can deploy your LangChain application as an OCI Data Science Model Deployment endpoint in a few lines of code. This blog post guides you through the process with step-by-step instructions.

LangChain


LLMs are a groundbreaking technology that encapsulate vast human knowledge and logical capabilities into a massive model. However, the current language model usage has many issues. The entire ecosystem is still evolving, resulting in a lack of adequate tools for developers to deploy language models.

LangChain is a framework for developing applications based on language models. Tasks like prompt engineering, logging, callbacks, persistent memory, and efficient connections to multiple data sources are standard out-of-the-box in LangChain. Overall, LangChain serves as an intermediary layer that links user-facing programs with the LLM. Through LangChain, combining other computing resources and internal knowledge repositories, we can advance various LLM models, toward practical applications based on the current corpus resources, providing them with new phased utility.

OCI model deployment


OCI Data Science is a fully managed platform for data scientists and machine learning (ML) engineers to train, manage, deploy, and monitor ML models in a scalable, secure, enterprise environment. You can train and deploy any model, including LLMs in the Data Science service. Model deployments are a managed resource in OCI Data Science to use to deploy ML models as HTTP endpoints in OCI. Deploying ML models as web applications or HTTP API endpoints serving predictions in real time is the most common way that models are productionized. HTTP endpoints are flexible and can serve requests for model predictions.

ADS SDK


The OCI Data Science service team maintains the ADS SDK. It speeds up common data science activities by providing tools that automate and simplify common data science tasks, providing a data scientist-friendly Pythonic interface to OCI services, most notably Data Science, Data Flow, Object Storage, and the Autonomous Database. ADS gives you an interface to manage the lifecycle of ML models, from data acquisition to model evaluation, interpretation, and model deployment.

Create your LangChain application


As an example, the following code builds a simple LangChain application to take a subject as input and generate a joke about the subject. Essentially it puts the user input into a prompt template and sends it to the LLM. Here, we use, Cohere as the LLM, but you can replace it with any other LLM that LangChain supports.

import os
from langchain.llms import Cohere
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

os.environ["COHERE_API_KEY"] = "<cohere_api_key>"

llm = Cohere()
prompt = PromptTemplate.from_template("Tell me a joke about {subject}")
llm_chain = LLMChain(prompt=prompt, llm=llm, verbose=True)</cohere_api_key>

Deploy the LangChain application using the Oracle ADS SDK


Now, you have a LangChain application, llm_chain, and you can easily deploy it to your model deployment using Oracle ADS SDK. The ADS SDK simplifies the workflow of deploying your application as a REST API endpoint.

Deploy LangChain applications as OCI model deployments

from ads.llm.deploy import ChainDeployment
ChainDeployment(chain=llm_chain).prepare_save_deploy(
    inference_conda_env="pytorch21_p39_gpu_v1",
    deployment_display_name="LangChain Deployment",
    environment_variables={"COHERE_API_KEY":"<cohere_api_key>"}
)</cohere_api_key>

Behind the scenes, ADS SDK automatically handles the following processes:

  • Serialization of the LangChain application: The configuration of the your application is saved into a YAML file.
  • Preparation of the model artifact, including some autogenerated Python code to load the LangChain application from YAML file and run it with the user’s input.
  • Saving the model artifacts to model catalog: This process uploads and registers your application as model in the model catalog.
  • Creating a model deployment: This deploys the scalable infrastructure to serve your application as HTTP endpoint.

Deploy LangChain applications as OCI model deployments

When the deployed model is active, you can use OCI CLI to invoke it. Replace the <langchain_application_model_deployment_url> with the actual model deployment URL, which you can find in the output from the previous step.

oci raw-request --http-method POST --target-uri <langchain_application_model_deployment_url>/predict --request-body ‘{“subject”: “animals”}’ --auth resource_principal</langchain_application_model_deployment_url>

Deploy LangChain applications as OCI model deployments

Source: oracle.com

Wednesday, September 27, 2023

Channels in OCI Queue enable messaging fairness, ephemeral destinations, and more

Oracle Cloud Infrastructure (OCI) Queue is a serverless asynchronous messaging service designed to handle large volumes of data with multiple concurrent producers and consumers of messages. When multiple producers and consumers are processing messages within the same queue, challenges can arise, such as the following examples: 

◉ An aggressive producer or a sudden volume burst from one producer can impact the performance of the application and cause a significant processing delay for messages coming from other producers.

◉ Certain request-response messaging patterns need ephemeral destinations, which are short-lived queues and meant for processing messages temporarily. While processing these messages in bulk, creating and deleting these short-lived queues can significantly increase the administrative overhead.

◉ When a queue has multiple consumers, individual consumers might be interested in consuming only certain types of messages or those coming from a specific producer, requiring developers to design a complex solution with multiple queues dedicated to each consumer type.

New: Channels in OCI Queue


To overcome these challenges, we’re announcing a new capability in OCI Queue: Queue channels. Channels enable ephemeral destinations within a queue and can improve message processing fairness, enable message selection, and request-response messaging patterns.

Messages published to a channel are available for consumption from both the queue and channel level. Channels don’t require explicit creation or deletion. While publishing a message, you can choose to specify a channel ID. All messages created with the same channel ID are published to the same channel. Channels are ephemeral, and if no messages are in a particular channel, the channel is deleted automatically. Channels share the same permissions, encryption method, and limits as their parent queue, but the queues can configure channel capacity, limiting the maximum amount of the queue’s overall capacity that a single channel can use at any time.

Enabling message processing fairness


When multiple producers are producing to the same queue, a sudden spike in message volume from one producer can cause a significant delay in processing messages from other producers. Sometimes, the application acts as a middleware for the end users, using a queue-per-end-user pattern, which requires the application to protect message consumption from skewing in favor of customers with higher traffic—the noisy neighbor problem.

In the following diagram, when the message producer (P1) starts producing messages in bulk, the messages from other producers (P2 or P3) can see a significant delay in processing.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

To consume messages from all the producers evenly and ensure message processing fairness, you must maintain separate queues for each producer type and implement a load balancing mechanism to consume messages evenly.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

With the introduction of channels, producers can now publish messages to a specific channel. When a consumer consumes messages from a queue without specifying a channel ID, the messages are returned from a random channel that has available messages. This separation not only helps increase fairness and protect against sudden volume spikes, but it allows you to use long polling for more effective data consumption.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

Enabling message selection

You can include an optional parameter in requests to select messages that were published with the matching the channel ID. OCI Queue returns available messages only from one of the channels that match the ID.

If multiple channels’ IDs match the selection in a request, messages are returned from a random channel that has available messages. If messages are published to a specific channel, but a consumption request doesn’t include a channel, messages are returned from a random channel with available messages.

Enabling Ephemeral Queues for Request-Response Pattern

The request-response ephemeral pattern is a well-established integration pattern that enables the sender application to send a request and provides a way for the receiver to correctly send a response back to the sender application. This pattern typically needs a short-lived queue or topic for the application to send responses to. Channels provide a simple solution that lets you create and delete multiple channels, which can be short-lived, without making any explicit CreateQueue or DeleteQueue API calls.

Multiple applications can send their requests to a single request queue, with a specific channel ID parameter set to uniquely identify the sender application. The receiver application can process the requests and send replies with the channel ID parameter to uniquely identify the sender that had published the message. The application that sent the request can then receive messages on the specific channel ID and correctly process the replies. When the message processes successfully and the consumer deletes it, the channel is automatically deleted if it has no more messages to process.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

Getting started with OCI Queue channels


Queue creation and channel capacity allocation

When creating or updating a queue, you can specify the percentage allocation for a channel to limit the maximum amount of the queue’s overall capacity that the channel can use at any time. By default, the limit is set as 100%, which means the channel can take up the entire queue’s bandwidth. If you set it up to 50%, the channel can take up only 50% of the queue’s bandwidth.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

Sending messages to a specific channel

You can send messages to a specific channel. If the channel doesn’t already exist, you can create another channel by specifying a channel ID while sending the message. If the channel ID isn’t specified, the message is sent to the parent queue.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

Listing channels

View the list of channels from the Channels page.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

Poll for messages from channels

From the Channels List page, poll message from a random or from a specific channel.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

Purge channel messages

You can purge messages from a specific channel using the Action menu of the specific channel.

Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials

Source: oracle.com

Wednesday, August 2, 2023

Transforming the organ matching and transplant journey with OCI Data Platform

In 2022, 4,111 heart transplants were performed in the US, averaging 29 transplants in 144 centers. More than 3,500 people wait for a new heart with 1 in 12 deaths. Every transplant is priceless, yet the promise is sacrificed with delayed recovery times, suboptimal matches, inadequate patient data, and transport logistics. The Organ Procurement and Transplantation Network (OPTN) is a public-private partnership that links all professionals, individuals, and volunteers who support the US donation and transplantation system. OPTN membership constitutes transplant centers, organ procurement organizations (OPOs), histocompatibility laboratories, public organizations, medical scientific members, and business and individual members. The United Network for Organ Sharing (UNOS) was awarded the initial OPTN contract on September 30, 1986 and continues to administer the OPTN today.

The OPTN calls for an integrated real-time, dynamic system with the following capabilities and features:

  • Extracts donor and recipient data from electronic health recovery (EHR) provider systems, such as EPIC and Cerner, and other patient-provider registries
  • Standardizes donor and recipient data to form a complete patient longitudinal record
  • Deidentifies the donor and recipient patient data
  • Algorithmic organ data matching, considering only medical and logistical criteria
  • Ensure timely and accurate organ delivery and monitoring
  • Real-time geolocation, rerouting, and organ matching based on organ viability
  • Historical data analytics capabilities for organizations and partners

Achieving all these goals requires a modern healthcare industry-compliant data platform to fulfill and scale these tasks efficiently and effectively.

Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Preparation, Oracle Database Guide, Oracle Database Tutorial and Materials

OCI architecture


The following diagram shows the architecture and key components of Oracle Cloud Infrastructure (OCI)’s solution to these issues:

Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Preparation, Oracle Database Guide, Oracle Database Tutorial and Materials

Key components


Data acquisition

The correct identification of data sources provides the foundation block for data acquisition, consisting of the following parts:

  • Donor and transplant candidate patient EHR data. The data is usually distributed across multiple providers, EHR systems, and donor registries. OPO donor registries provides the required filtration to pull EHR data for donors only.
  • Transplant candidate or recipient data also follows the same process, but recipient-specific registries might not be maintained.
  • Radiology data sources provides annotated images related to the donor
  • Organ tracking sensors provides real-time streaming geolocation and organ vitality during transport.

This process uses the following data platform features:

  • Encrypted and secured ingestion of data
  • Industry standard complaint data formats, such as HL7 and FHIR
  • Industry standard acquisition protocols, such REST and MQTT
  • Industry standard tools, such as Oracle Integration Cloud (OIC), Oracle streaming, and Oracle internet of things (IOT)

EHR data standardization

Data standardization transforms EHR input data into common representations with a single, consistent view of the patient longitudinal record from data stored across disparate systems. Data standardization has the following key elements:

  • Accurately compare data between systems
  • Parsing individual data elements to a common format
  • Data cleansing
  • Normalization (converting nicknames and short names to standardized names)
  • Data typing standardized into a common data type
  • Phonetic encoding, such as common names based on sound

Common popular standardization frameworks include the following examples:

  • Finite state machine (FSM) framework: Process encompassing multiple states where configurable rules are applied on each state. FSM includes steps like cleansing, tokenization, parsing and ambiguity resolution.
  • Patterns based framework: Process defined in configurable dictionaries enabling detectable patterns by data types. Typical steps include parsing, data type identification, normalization, and patterns resolution.

Published by HL7, Fast Healthcare Interoperability Resources (FHIR) is a standard for healthcare data exchange that supports web exchange standards formats like XML, JSON, HTTP, OAuth with RESTful architectures, and service-based architectures. Oracle Healthcare data repository and Oracle Health Master Person Index (OHMPI) provides a way to use FHIR to create patient longitudinal record efficiently and accurately.

Patient data deidentification

Patient health information (PHI) deidentification is not only required for medical research studies, comparative effectiveness studies, and policy assessments, but also in PHI agnostic matching, such as organ matching. Common industry practices include the following examples:

  • Safe-harbor method: Remove standard PHI attributes (About 18 types) such as names, identifiable numbers such as phone, account, biometric identifiers, full face photos, and license numbers. The process is widely followed and easier to automate and implement.
  • Expert determination: Requires that a healthcare statistical expert can corelate risks associated with identified attributes to justify its removal. This process is more time- and resource-intensive, custom, and provides greater accuracy.

Multiple implementations convert healthcare data into a common FHIR formats before turning it to a deidentification engine that uses the safe-harbor method for deidentification. Typical tools for deidentification consist of data redaction, dateshift, perturb, cryptohash, encrypt, substitute, and generalize.

A different method involves deidentification at the FHIR layer, which is more secure. This process involves deidentification at rest at the database or store level. Open source BERT transformer models like BioBert pretrained models, trained on several medical corpora like journals, medical articles, and publications of medical research, provide context-aware embeddings, and PHI named entity recognition (NER) can be used to clean or mask PHI identifiers.

Typically, OCI Data Science tools like OCI Autonomous Data Warehouse or OCI AI Language services and OCI Data Science platform are geared for open source deidentification processes and customizations to produce the desired outcome.

Organ matching and continuous improvement

Important key factors for matching are not only the medical factors like blood type, height, weight, and organ size but also geolocation distance between the donor and recipient, organ life, and the transport time. The organ matching process must include real-time, automated, and flexible outcomes, matching across many recipients requiring a continuous allocation process instead of a categorical with a few data points. The computation of a real-time predictive matching score must consider between continuously data updates from EHRs, geo-location, and organ vitality data streams and transplant candidate conditions.

Matching involves comparing specific fields in two standardized records and returning a weight that indicates the likelihood of a match between the two records. A higher weight between two records indicates a greater likelihood of a match. Data matching can be either deterministic or probabilistic. In deterministic matching, either record unique identifiers are compared to determine a match or an exact comparison is used between attributes. Because this process has some limitations in a probabilistic matching, several field values are compared between two records and each field is assigned a weight that indicates how closely the two field values match. Custom matching thresholds, optimum or ceiling matching, and un-matching conditional probabilities—m-prob and u-prob—allow the process to specify the range of attributes that match most to least.

You can achieve data matching using two flavors of the OCI infrastructure presented in the architecture. You can implement and tune both to determine the optimal matching. Each process has the following key points:

  • Prebuilt matching using OHMPI
    • Provides generic data matching methodology with a match engine framework with a choice of customizable parameters and weights
    • The setup is low-code, quick, database centric, runs within an Oracle Database application and is configuration-driven.
  • Flexible custom matching at scale using Oracle Container Engine for Kubernetes (OKE) and DevOps containers

Messaging and notifications

With multiple systems like donor data ingestion, deidentification, and geolocation sensing interacting to provide a real-time organ matching scenario, the communication between these systems must be robust, resilient, native to the cloud, and follow a standard unified messaging protocol. OCI Events and Notification services hub and functions provide the necessary infrastructure. These service are compliant with the Cloud Native Computing Foundation (CNCF) industry standard and allow interoperability between systems within OCI and across OPOs and other external systems. Rules defined on OCI services emitting events trigger various workflow steps with OCI Functions and Notification services. Typical scenarios include the following examples:

  • Initiation of the donor or recipient ingestion based on donor organ availability by OPOs
  • Initiation of donor and recipient FHIR standardization process
  • Preparing deidentified data at donor and transplant candidate levels
  • Triggering organ matching process based on organ availability, geo-location, organ viability, and other attributes
  • Status update transplant candidate on organ match
  • Status update operational monitoring of the system

You can use OCI Functions and Notification for the following processes:

  • Customizing OHMPI and IOT ingestion and standardization using the product REST API interface
  • You can also use Functions if using container-based architectures for match runs.

Organ transportation and health monitoring

Real-time organ health monitoring at rest or in motion is essential to validate the actual life of an organ before a transplant. This method aids or eliminates the need for organ viability checks because it reaches the transplant surgeons hands. The delivery is performed with real-time analysis of organ vitality and geolocation data streamed from the organ transport containers. With a short organ vitality window, transplants today are restricted by short geolocation distances between donor and recipient. Also, rematching and rerouting based on organ vitality data aren’t typically performed but highly wanted.

This process requires the following factors:

  • An efficient sensor based container that can stream data to a cloud data lakehouse continuously
  • A cold chain logistics provider responsible for delivery to the last mile
  • An effective and integrated rematching and rerouting system to find the next transplant candidate if needed
  • The streaming system provides established interfaces, such as API, across different cold chain logistics transportation vendors.
  • Transportation firms, such as Fedex and UPS, can provide API-based organ vitality and geolocation data to be quickly consumed.

The IoT service is geared to provide the following benefits:

  • Flexibility in streaming device adaptation, such as a IoT-enabled gateway, directly connected gateway or third-party gateway
  • Ingesting and integrating data from a multitude of payloads and brokers, such as HTTP or MQTT
  • Connect to OCI using Oracle Integration Cloud (OIC) and Oracle Analytics Cloud (OAC) adaptors and REST API
  • Simulation match testing possibility using a digital twin scenario

Transplant research

Transplant research areas aim to understand best practices and improve performance with a goal to increase transplants. Data inputs such as organ offer outcomes, transplant operations benchmarks, Key indicators, compliance, and performance are several key areas outlined by UNOS. However, deidentified patient records, match run outcomes, and the streaming organ vitality attributes provide a unified data platform for the researchers to investigate further. The OCI Data Platform can provide the following features and benefits:

  • A deidentified dataset access for donors and transplant patients for research
  • Patient historical and longitudinal records and geolocation attributes
  • Match run outcomes, match criteria, and match history
  • Any organ vitality attributes of importance, such as temperature and pH
  • Post-transplant outcomes

OCI Data Platform aids researchers with predictive model-based and open source data tools, such as Oracle Data Science, Spark-based real-time analytics tools, such as OCI Data Flow, OCI Streaming, and in-database ML tools within OCI Autonomous Database. This availability facilitates researchers to perform analysis directly on live and current deidentified datasets to develop models, operationalize them to test model drifts and their efficacies, operate between the cloud and local laptops or other on-premises systems, and integrate with other public data sources or pretrained and developed models. OCI CPU, GPU, and high-performance computing (HPC) Compute shapes also facilitate researchers to large, simulated workloads.

Organ transplant analytics

UNOS currently publishes many analytic reports for OPOs and the community, including the following examples:

  • Transplant benchmark reports: Customizable comparative reports providing insights to population listing practices and transplant activity for UNOS members at regional and national levels
  • Organ offer outcomes: A dashboard for visualizing organ acceptance by donor type with transplant and aggregate specific outcomes
  • Transplant compliance and performance reports: Clarifies post-transplant outcomes, waitlist outcomes by transplant and mortality and demographic waitlist by diagnosis, active status, and medical urgency factors
  • Executive level measures: Waitlist additions and management, organ offer characteristics, transplants performed, post-transplant stay, 24-hour high-level indicators, and trends
  • Enhanced staffing survey and analytics: Staffing survey experience in conjunction with transplant administration

However, these reports lack the self-service, scalability, unification, and extensibility features that a modern cloud based data platform provides. OAC with Oracle Autonomous Database on OCI Lakehouse provides the following benefits:

  • Operational dashboard covering the end-to-end organ transplant process
  • Real-time insights from the matching process
  • Customizable predictive match model simulations to aid researchers
  • Descriptive and historical data analysis on transplants
  • Prebuilt and custom reports and automated delivery from a cloud analytics system

Key takeaways of using an enterprise data platform

Implementing an enterprise cloud-based health data platform in OCI offers the following benefits:

  • Tools and integrations: The right combination of prebuilt applications, data platform tools and services, and compute infrastructure is required for successfully operating a complex data platform. OCI offers the following advantages:
    • Health industry-specific, such as HL7, and other industry-standard data source integration support with OIC adapters
    • Streaming provider and device integration flexibility with out-of-the-box adapters with OCI IoT
    • Prebuilt, configurable data-matching algorithm implemented inside the database with OHMPI and Oracle Autonomous Database
    • A flexible platform to quickly deploy code and orchestrate at scale with OCI Kubernetes engine
    • An out-of-the-box cloud based prebuilt event and notification system implementable across the entire organ transplant data fabric
    • A configurable and cloud-based analytic dashboard, reporting, and delivery solution with OAC
    • A unified data catalog to maintain the source of truth across participating data members in the system
  • Prebuilt health industry and government certifications: With a data platform typically operating in a hybrid multicloud environment, healthcare attestations are required at various areas of data residency. OCI Data Platform can provide attestations along the cloud boundaries and inside. OCI provides HIPPA, HITRUST CSF, and FedRamp compliance attestations. 
  • Healthcare data standardizations: Healthcare data standardizations involve more than standardizing healthcare codes. They involve various data normalizations, configuring and customizing standard data quality practices, and evolution over time. Healthy standardization requires a mix of prebuilt, configurable, and customizable platform aspects where you can take on more development by sourcing various open source libraries. OCI provides seamless standardization across healthcare applications, FHIR at EHR data ingestion, and a platform to develop custom Python libraries.
  • Scalability, performance, and cost: The utility value of this system is best realized when it automatically scales maintaining the same or higher performance at a decreasing cost rate. OCI Data Platform offers the following benefits:
    • A unified object storage-based data lakehouse to ingest various types of unstructured data and scalable autonomous data warehouse
    • A customizable data retention and archival features with OCI Object Storage and automatically managed backups and patches with live relational data storage
    • A scalable compute infrastructure with a wide range of CPU and GPU Compute shapes
  • Unified integration of tools and services platform: Most enterprise data platform spans and integrates across EHR data providers and tools to provide for real-time delivery and monitoring needs. OCI provides the following features:
    • A multicloud data platform across multiple EHR providers, healthcare integrations such as HL7 and FHIR, and data access through REST APIs and HTTP.
    • OIC provides necessary data transformations and imputations during ingestion
    • A unified cloud native event and messaging system that can operate independently and securely in isolation and provide for the needed workflow dependencies
Source: oracle.com

Monday, July 24, 2023

Effortlessly set up customized clusters with OCI Big Data cluster profiles

Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Prepartion, Oracle Database Guides, Oracle Database Tutorial and Materials, Oracle Database Guides Exam

The Oracle Cloud Infrastructure (OCI) Big Data service with Apache Hadoop is a fully managed cloud service from OCI that allows you to process big data workloads using popular open source frameworks, such as Hadoop, Spark, Hive, and HBase. One of the features of OCI Big Data is the ability to create and manage Hadoop clusters of different profiles or types. In this blog post, we discuss the cluster profile feature in OCI Big Data, its benefits, and how to use it.

What is OCI Big Data?


OCI Big Data is a cloud-based big data processing service offered by OCI. The fully managed platform enables customers to process large amounts of data using popular open source big data frameworks, such as Hadoop, Spark, Hive, and Kafka. The service is designed to simplify the process of deploying and managing big data solutions, and you can integrate it with other OCI services and on-premises systems.

Use cases for Oracle Big Data


The following examples show the top use cases for OCI Big Data:

  • ETL processing: Extract, transform, load (ETL) is a common use case for OCI Big Data. You can use OCI Big Data to process large amounts of data, transform it into a format suitable for analysis, and load it into a data warehouse or other storage system.
  • Data analysis: You can use OCI Big Data for data analysis and data exploration. You can use OCI Big Data to run Apache Spark jobs to analyze data and generate insights—useful for business intelligence, data visualization, and machine learning (ML) applications.
  • Machine learning: You can use OCI Big Data for ML applications to train models on large datasets and then use the models for prediction and other tasks.
  • Log processing: With OCI Big Data, you can process analyze log data from web servers, application servers, and other sources to identify patterns and trends.
  • Batch processing: You can use OCI Big Data to process large amounts of data in batches, for example, to generate reports or perform calculations.
  • Real-time processing: You can use OCI Big Data to process streams of data in real-time, for example, to perform fraud detection or anomaly detection.

Why customers love OCI Big Data service


Customers love OCI Big Data, a cloud-based big data analytics service, for the following common reasons:

  • Scalability: OCI Big Data can easily scale to handle large amounts of data and processing power, enabling customers to gain insights quickly and efficiently.
  • Compatibility: OCI Big Data supports various open source big data frameworks, such as Hadoop, Spark, Hive, and Kafka, which allows customers to use the tools they’re familiar with and use existing code.
  • Security: OCI Big Data offers robust security features, including encryption at rest and in transit, and integrated authentication with OCI Identity and Access Management (IAM) service, providing customers with peace of mind that their data is protected.
  • Flexibility: Customers can choose to deploy OCI Big Data in various ways, including using preconfigured clusters or creating custom clusters with specific configurations, enabling them to tailor the service to their specific needs.
  • Integration with other OCI services: OCI Big Data integrates with other OCI services, such as OCI Data Catalog, OCI Data Flow, and OCI Lake House, and OCI makes it easy for customers to build end-to-end solutions for their big data needs.

What is a cluster profile?


A cluster profile in OCI Big Data represents a preconfigured set of resources optimized for a particular workload or use case. Each cluster profile has a predefined set of configuration parameters that are optimized for a specific data processing job. For example, OCI offers cluster profiles for Hadoop, Spark, HBase, Hive, and Trino (Interactive query), each designed for specific workloads and use cases.

Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Prepartion, Oracle Database Guides, Oracle Database Tutorial and Materials, Oracle Database Guides Exam

Hadoop

The Hadoop cluster type in OCI Big Data is designed to work with Hadoop Distributed File System (HDFS) and MapReduce. It’s ideal for batch processing, such as data warehousing, log analysis, and ETL. The Hadoop cluster type comes with Hadoop, Hive, Pig, and Oozie preinstalled, making it easy to get started with big data processing.

Spark

The Spark cluster type in OCI Big Data is designed to work with Apache Spark, an open source data processing framework that supports both batch and streaming data processing. It’s ideal for real-time data processing, machine learning, and graph processing. The Spark cluster type comes with Spark, Hive, and Jupyter preinstalled, making it easy to start using Spark for big data processing.

HBase

The HBase cluster profile in OCI Big Data is designed to work with Apache HBase, an open source NoSQL database that runs on top of Hadoop. It’s ideal for storing and retrieving large amounts of structured data, such as sensor data, social media data, and financial data.

Trino

This cluster profile is for interactive querying of large datasets. Trino returns results to you as soon as they’re available. This availability offers data analysts and data scientists the ability to query large amounts of data, test hypotheses, run A/B testing, and build visualizations or dashboards.

Kafka

This cluster profile is designed for streaming data processing and supports Apache Kafka.

Hadoop Etxended

We used this cluster profile before the profile feature was introduced.

Benefits of cluster profiles


The use of cluster profile provides the following benefits:

  • Faster cluster deployment: The use of preconfigured cluster profiles speeds up the deployment process by reducing the amount of manual configuration required.
  • Better performance: Cluster profiles are optimized for specific workloads, providing better performance compared to a generic cluster setup.
  • Simplified management: Each cluster profiles comes with preconfigured services, reducing the need for manual configuration and simplifying cluster management.

How to use cluster profiles in OCI Big Data


To create an OCI Big Data cluster using a specific cluster profile, use the following steps:

  1. In the Oracle Cloud Console, navigate to the OCI Big Data service.
  2. Click the Create cluster button.
  3. Enter the cluster name and admin password.
  4. Select the checkbox for Secure and Highly Available (HA) to make the cluster secure and highly available.
  5. Select the distribution and version of Hadoop from either Oracle’s Distribution of Hadoop (ODH) or Cloudera’s Distribution of Hadoop (CDH).
  6. Select the cluster profile that best suits your use case from the menu. You can also select the version of the cluster type that you want to use.
  7. Select from the Compute shape, block storage for master and utility, and the number of Compute shape options for the worker nodes.
  8. Provide the network related details, such as CIDR Block, virtual cloud network (VCN), and subnet details.
  9. Select your encryption type: Oracle-managed or customer-managed.
  10. Click Create to provision the Big Data cluster.

When the cluster is created, off you go! You can use it to process Big Data workloads using the services and tools enabled by default.

Source: oracle.com

Wednesday, March 29, 2023

Automate media processing jobs

In today’s fast-paced world, delivering high-quality media content to a global audience has become a critical aspect of many businesses. The traditional methods of media delivery, such as satellite and terrestrial networks, are becoming less feasible because of the high costs, complexity, and limitations associated with these systems.

Here, the Oracle Cloud Infrastructure (OCI) Media Flow service comes in as a game changer in the media delivery landscape. In this blog, we review how we can automate media processing with OCI Media Flow using OCI prebuilt functions.

What is Media Flow?


OCI Media Flow is a cloud-based media processing solution provided by Oracle Cloud Infrastructure. It provides a flexible and scalable platform for delivering high-quality video content over the internet to a global audience. The solution uses the power of OCI’s highly available and secure infrastructure to deliver a reliable and high-quality media delivery experience to end-users.

OCI Media Flow provides processing through media workflow-based approach. You can customize the media workflow to do tasks like transcodes, speech to text outputs, object detection, text detection, and thumbnail generations. After a media workflow is configured, you can create media workflow jobs to run for each media file that needs the processing. These media files must be on OCI Object Storage for the media workflow job to pick it up for processing. After processing, the output files are sent to OCI Object Storage and optionally also to OCI Media Streams.

Why automate media processing?


Media files can be large when they come from a camera, and often they need edits to make the video or audio more reachable for the audience. OCI Media Flow requires you to pass the media file details to the media workflow job. So, if you have 100 files to process, select those 100 files to submit 100 media workflow jobs. This process is doubtlessly time-consuming and costly.

How to automate media processing


OCI now offers prebuilt functions that allow you to create OCI Function solutions using standard codes from Oracle that you can use and not manage. In the prebuilt functions catalog, we have a “Media Workflow Job Spawner” code that lets you automate those 100 jobs to be processed as they’re uploaded to OCI Object Storage.

Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Tutorial and Materials

Source: oracle.com

Friday, January 13, 2023

Configure OCI DataFlow Interactive Notebook & Access Autonomous DataWarehouse & Object Storage

Oracle Cloud Infrastructure (OCI) Data Flow is a fully managed big data service that lets you run Apache Spark applications at any scale with almost no administration. Spark has become the leading big data processing framework and OCI Data Flow is the easiest way to run Spark in Oracle Cloud because there’s nothing for developers to install or manage.

Now perform your analytics on OCI DataFlow using Interactive Data Science Notebook:


OCI DataFlow is now coming with Interactive OCI Data Science Notebook. Now, users can seamlessly enable and start playing with their data using the Data Science Notebook. This Notebook experience leverages the power of Apache Spark. Here, We will see how easily an OCI DataFlow Environment can be created on OCI using Conda. We will be creating OCI Data Science session & Notebook and will access OCI Dataflow spark platform using Livy session. Submit fault-tolerant Spark jobs from the notebook using synchronous and asynchronous methods to retrieve the output.

OCI DataFlow with Interactive OCI Data Science have also introduced SparkMagic commands adding it's own flavours & upgrades. SparkMagic allows for interactive communication with Spark using Livy. Using the `%%spark` magic directive within a JupyterLab code cell.

The purpose of this document is to walk you through the setup required to access the OCI Data Flow Sessions through the Data Science Notebook Session. These Sessions allow you to run interactive Spark workloads on a long lasting Data Flow cluster through an Apache Livy integration. 

Also, Once OCI Data Flow Spark Session is created, will go through some Sample codes for performing Spark Operations on OCI Object Storage &  Autonomous DataWarehouse.

Features & Benefit:

◉ Use Interactive Jupyter Notebook with OCI Data Flow. 
◉ Data Flow Sessions supports auto-scaling Data Flow cluster capabilities. User can enable auto-scaling while creating Spark - Livy session as well as once the session is created from the Notebook.
◉ Data Flow Sessions supports the use of conda environments as customizable Spark runtime environments. 
◉ Import open source libraries & start using it after building Conda environments. 
◉ Spark Delta Lake in OCI Data Flow & perform ACID transactions. 

Use Interactive OCI Data Science Notebook with OCI Data Flow:


To use the OCI Data Science Notebook with OCI Data Flow, follow below steps:

◉ Create required buckets 
    ◉ Create a bucket named dataflow-logs in your tenancy. 
    ◉ Create a bucket named dataflow-warehouse in your tenancy. 
◉ Create a dynamic group in a specific compartment:

ALL {resource.type='dataflowrun', resource.compartment.id='<compartment_id>'}

ALL {resource.type='datasciencenotebooksession', resource.compartment.id='<compartment_id>'}

Any {resource.type = 'datacatalogmetastore'}

◉ Create a policy to manage OCI resources from OCI data flow, Data Science:

ALLOW DYNAMIC-GROUP <df-dynamic-group> TO MANAGE objects IN TENANCY WHERE ANY
{target.bucket.name='<bucket_name>',
target.bucket.name='dataflow-logs,
target.bucket.name='dataflow-warehouse'
}

ALLOW DYNAMIC-GROUP '<ds-dynamic-group>' TO MANAGE dataflow-family
in compartment '<your-compartment-name>'

ALLOW DYNAMIC-GROUP '<df-dynamic-group>' TO MANAGE data-catalog-metastores IN TENANCY

ALLOW DYNAMIC-GROUP '<dcat-hive-group>' TO READ buckets IN TENANCY

ALLOW DYNAMIC-GROUP '<dcat-hive-group>' TO MANAGE object-family IN TENANCY WHERE ANY
{ target.bucket.name = '<bucket_name>',
target.bucket.name = '<managed-table-location-bucket>',
target.bucket.name = '<external-table-location-bucket>'
}

ALLOW DYNAMIC-GROUP '<ds-dynamic-group>' TO MANAGE objects IN TENANCY
WHERE ALL {target.bucket.name='ds-conda-env'}

ALLOW DYNAMIC-GROUP '<df-dynamic-group>' TO MANAGE objects IN TENANCY
WHERE ALL {target.bucket.name='ds-conda-env'}

◉ Create OCI Data Science Project & Session.

Autonomous DataWarehouse & Object Storage, Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Database Tutorial and Materials

◉ Open New OCI Data Science Session. From File option,  choose New Launcher and click on Terminal.

Autonomous DataWarehouse & Object Storage, Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Database Tutorial and Materials

◉ Install and activate the pyspark32_p38_cpu_v1  conda environment from your terminal:

odsc conda install -s pyspark32_p38_cpu_v1
source activate /home/datascience/conda/pyspark32_p38_cpu_v1

◉ Once Conda is activated, Goto New Launcher Tab & click on Settings. Fill required information about object storage where Conda package will be uploaded & save it.

Autonomous DataWarehouse & Object Storage, Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Database Tutorial and Materials

◉ Now, Publish Conda environment:

odsc conda publish -s pyspark3_2anddataflowv1_0

Note: Publishing will take some time. Once it is completed, you can observe Conda package is uploaded on the Object Storage bucket.

◉ Open Notebook using "PySpark and DataFlow" as kernel from new Launcher.
◉ Execute below commands to setup and create Data Flow Spark session using Livy Service:

1. Setup Authentication using ADS

import ads
ads.set_auth("resource_principal") # Supported values: resource_principal, api_key

2. Load Extension

%load_ext dataflow.magics

3. Create OCI DataFlow Spark Session using Livy:

#Create OCI Dataflow Session using LIVY service through OCI Data SCience Notebook.
import json
command = {
    "compartmentId": "ocid1.compartment.oc1..xxxxxxxxxxxxxx",
    "displayName": "Demo_DataFlow_Spark_v1",
    "sparkVersion": "3.2.1",
    "driverShape": "VM.Standard.E3.Flex",
    "executorShape": "VM.Standard.E3.Flex",
    "driverShapeConfig":{"ocpus":1,"memoryInGBs":16},
    "executorShapeConfig":{"ocpus":1,"memoryInGBs":16},
    "numExecutors": 1,
    "logsBucketUri": "<oci://bucket@namespace/>",
    "archiveUri": "<oci://bucket@namespace/archive.zip>"
    "configuration":{"spark.archives":"<oci://bucket@namespace/>#conda",
                     "spark.oracle.datasource.enabled":"true"}
}

command = f'\'{json.dumps(command)}\''
print("command",command)

#"configuration":{
#    "spark.dynamicAllocation.enabled":"true",
#    "spark.dynamicAllocation.shuffleTracking.enabled":"true",
#    "spark.dynamicAllocation.minExecutors":"1",
#    "spark.dynamicAllocation.maxExecutors":"4",
#    "spark.dynamicAllocation.executorIdleTimeout":"60",
#    "spark.dynamicAllocation.schedulerBacklogTimeout":"60",
#    "spark.dataflow.dynamicAllocation.quotaPolicy":"min" }}'

%create_session -l python -c $command

Autonomous DataWarehouse & Object Storage, Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Database Tutorial and Materials

OCI Data Flow Spark Session is created. Moving ahead will go through some Sample codes for performing Spark Operations on:


1. OCI Object Storage
2. OCI Autonomous DataWarehouse

◉ Now, You can Import dependent libraries in Session:

%%spark
#Import required libraries.

import json
import os
import sys
import datetime
import oci
import pyspark.sql 
from pyspark.sql.functions import countDistinct

from delta.tables import *

◉ Perform Spark Read operation on Object Storage.  

Read Object Storage file using spark.read from Livy Session:

<strong>%%spark -o df_Bronze_Insurance_Data</strong>

#Read Claim Insurance files from OCI Object Storage in Spark Dataframe.

df_Bronze_Insurance_Data = spark.read.format("csv").option("header", "true") \
.option("multiLine", "true").load("oci://test-demo@OSNamespace/insur_claim/claim.csv*")

print("df_RawZone_Data",df_Bronze_Insurance_Data)
df_Bronze_Insurance_Data.show(5)

Autonomous DataWarehouse & Object Storage, Oracle Database, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Database Tutorial and Materials

◉ Perform Spark Write operation on Object Storage.  

%%spark
df_Bronze_Insurance_Data.write.format("json").option("mode","overwrite").save("oci://test-demo@OSNamespace/insur_claim/claim_curated")

◉ Perform Read & Write Operation on Autonomous DataWarehouse:

    ◉ Load Data into ADW using Secret Vault for Wallet: 

Copy below code as it is. 

Reference: https://github.com/oracle-samples/oracle-dataflow-samples/tree/main/python/loadadw

%%spark

def get_authenticated_client(token_path, client, file_location=None, profile_name=None):
    """
    Get an an authenticated OCI client.
    Example: get_authenticated_client(token_path, oci.object_storage.ObjectStorageClient)
    """
    import oci

    if not in_dataflow():
        # We are running locally, use our API Key.
        if file_location is None:
            file_location = oci.config.DEFAULT_LOCATION
        if profile_name is None:
            profile_name = oci.config.DEFAULT_PROFILE
        config = oci.config.from_file(file_location=file_location, profile_name=profile_name)
        authenticated_client = client(config)
    else:
        # We are running in Data Flow, use our Delegation Token.
        with open(token_path) as fd:
            delegation_token = fd.read()
        signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner(
            delegation_token=delegation_token
        )
        authenticated_client = client(config={}, signer=signer)
    return authenticated_client

def get_password_from_secrets(token_path, password_ocid):
    """
    Get a password from the OCI Secrets Service.
    """
    import base64
    import oci

    secrets_client = get_authenticated_client(token_path, oci.secrets.SecretsClient)
    response = secrets_client.get_secret_bundle(password_ocid)
    base64_secret_content = response.data.secret_bundle_content.content
    base64_secret_bytes = base64_secret_content.encode("ascii")
    base64_message_bytes = base64.b64decode(base64_secret_bytes)
    secret_content = base64_message_bytes.decode("ascii")
    return secret_content

def get_delegation_token_path(spark):
    """
    Get the delegation token path when we're running in Data Flow.
    """
    if not in_dataflow():
        return None
    token_key = "spark.hadoop.fs.oci.client.auth.delegationTokenPath"
    token_path = spark.sparkContext.getConf().get(token_key)
    if not token_path:
        raise Exception(f"{token_key} is not set")
    return token_path    

def get_temporary_directory():
    if in_dataflow():
        return "/opt/spark/work-dir/"
    else:
        import tempfile
        return tempfile.gettempdir()

def in_dataflow():
    """
    Determine if we are running in OCI Data Flow by checking the environment.
    """
    if os.environ.get("HOME") == "/home/dataflow":
        return True
    return False

def download_wallet(spark, wallet_path):
    """
    Download an ADW/ATP wallet file and prepare it for use in a Data Flow
    application.
    """
    import oci
    import zipfile

    # Get an object store client.
    token_path = get_delegation_token_path(spark)
    object_store_client = get_authenticated_client(
        token_path, oci.object_storage.ObjectStorageClient
    )

    # Download the wallet file.
    from urllib.parse import urlparse
    parsed = urlparse(wallet_path)
    bucket_name, namespace = parsed.netloc.split("@")
    file_name = parsed.path[1:]
    response = object_store_client.get_object(namespace, bucket_name, file_name)
    temporary_directory = get_temporary_directory()
    zip_file_path = os.path.join(temporary_directory, "wallet.zip")
    with open(zip_file_path, "wb") as fd:
        for chunk in response.data.raw.stream(1024 * 1024, decode_content=False):
            fd.write(chunk)

    # Extract everything locally.
    with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
        zip_ref.extractall(temporary_directory)

    # Distribute all wallet files.
    contents = "cwallet.sso ewallet.p12 keystore.jks ojdbc.properties sqlnet.ora tnsnames.ora truststore.jks".split()
    spark_context = spark.sparkContext
    for file in contents:
        spark_context.addFile(os.path.join(temporary_directory, file))

    return temporary_directory

◉ Set below Parameters related to ADW Instance & Wallet.

%%spark
PASSWORD_SECRET_OCID = "ocid1.vaultsecret.oc1.phx.xxxxxxx"
TARGET_TABLE = "ADMIN.TB_NAME"
TNSNAME = "demolakehouseadw_medium"
USER = "admin"
WALLET_PATH = "oci://bucketname@osnamespace/Wallet_DemoLakeHouseADW.zip"

# Download and distribute our wallet file.
wallet_path = download_wallet(spark, WALLET_PATH)
adw_url = "jdbc:oracle:thin:@{}?TNS_ADMIN={}".format(TNSNAME, wallet_path)

◉ Now, Get password using the secret service.

%%spark
# Get our password using the secret service.
print("Getting wallet password")
token_path = get_delegation_token_path(spark)
password = get_password_from_secrets(token_path, PASSWORD_SECRET_OCID)
print("Done getting wallet password")

# Save the results to the database.
print("Saving processed data to " + adw_url)
properties = {
    "driver": "oracle.jdbc.driver.OracleDriver",
    "oracle.net.tns_admin": TNSNAME,
    "password": password,
    "user": USER
}

◉ Read Sample Table from ADW. 

%%spark
SOURCE_TABLE = "ADMIN.RETAILPOS"
df_RetailPOS_15min = spark.read.jdbc(url=adw_url, table=SOURCE_TABLE, properties=properties)

◉ Load above Dataframe into ADW. 

%%spark

#Load into ADW:

TARGET_TABLE = "ADMIN.RETAILPOS_15MINUTES"
print("TARGET_TABLE : ",TARGET_TABLE)

# Write to ADW.
print("Write to ADW : ")
df_RetailPOS_15min.write.jdbc(url=adw_url, table=TARGET_TABLE, mode="Append", properties=properties)
print("Writing done to ADW : ")


Source: oracle.com