Thursday, April 25, 2024

Generative Artificial Intelligence (AI) refers to a subset of AI algorithms and models that can generate new and original content, such as images, text, music, or even entire virtual worlds. Unlike other AI models that rely on pre-existing data to make predictions or classifications, generative AI models create new content based on patterns and information they have learned from training data.

One of the most well-known examples of generative AI is Generative Adversarial Networks (GANs). GANs consist of two neural networks: a generator and a discriminator. The generator network creates new content, while the discriminator network evaluates the content and provides feedback to the generator. Through an iterative process, both networks learn and improve their performance, resulting in the generation of more realistic and high-quality content.

Generative AI has made significant advancements in various domains. In the field of computer vision, generative models can create realistic images or even generate entirely new images based on certain prompts or conditions. In natural language processing, generative models can generate coherent and contextually relevant text, making them useful for tasks like text summarization, translation, or even creative writing.

However, it is important to note that generative AI models can sometimes produce biased or inappropriate content, as they learn from the data they are trained on, which may contain inherent biases. Ensuring ethical and responsible use of generative AI is an ongoing challenge in the field.

Generative AI also presents exciting opportunities for creative industries. Artists can use generative models as tools to inspire their work or create new forms of art. Musicians can leverage generative AI models to compose music or generate novel melodies.

Overall, generative AI holds great potential for innovation and creativity, but it also raises important ethical considerations that need to be addressed to ensure its responsible and beneficial use in various domains.

Some examples of text generation models include ChatGPT, Copilot, Gemini, and LLaMA which are often collectively referred to as chatbots. They generate human-like responses to queries. Image generation models include Stable Diffusion, Midjourney, and DALL-E which create images from textual descriptions. Video generation models include Sora which can produce videos based on prompts. Other domains where Generative AI finds applications are in software development, healthcare, finance, entertainment, customer service, sales, marketing, art, writing, fashion, and product design.

In Azure, a copilot can be developed with no code using Azure OpenAI studio. We just need to instantiate a studio, associate a model, add the data sources, and allow the model to train. The models differ in syntactic or semantic search. The latter uses a concept called embedding that discovers the latent meaning behind the occurrences of tokens in the given data. So, it is more inclusive than the former. A search for time will specifically search for that keyword with the GPT-3 but a search for clock will include the references to time with a model that leverages embeddings. Either way, a search service is required to create an index over the dataset because it facilitates fast retrieval. A database such as Azure Cosmos DB can be used to assist with vector search.


Wednesday, April 24, 2024

 This is a continuation of previous articles on IaC shortcomings and resolutions. In this section, we discuss the IP restrictions between sender and receiver in cloud resources. Let us take the example of an application gateway and app services behind the gateway.  As a layer 7 resource, http proxy and http request rewrite capabilities, the gateway routes traffic by path to different app services. These app services can allow promiscuous web traffic or specify origin ip restrictions via ip restriction rules. With the rules specifying origin as gateway, there is some hardening but there is no restrictions to who the caller are behind the gateway and app services have the potential to determine that as well.

This is where some co-operation is needed between the application gateway and the app services. The gateway automatically adds additional headers to indicate the source ip of the traffic. The app services would have a rule for the gateway indicating the source ip block for the gateway typically in an ip-address-with-/32 prefix notation and additional filters for matching the values of anticipated source ip ranges behind the gateway. There are four headers in all out of which the x_forwarded_host and x_forwarded_for bear the hostnames and the ip ranges. 

The x_forwarded_host seldom works when the gateway hostname is specified. This is not a shortcoming but header is used to identify the original host requested by the client in the Host HTTP request header and since name to ip resolutions might involve several layers of resolution, the values specified in the header for the clients might not agree. It is useful in the case where the reverse proxies such as load balancers or CDNs are involved, the host names and ports may differ from the origin server handling the request. With SSL termination, the source IP becomes that of the gateway and so this header preserves the original url’s location. Leaving this header blank and using the other header works in most deployments.

The X-Forwarded-For header provides information about the client’s IP address (or a chain of proxy IP addresses) that initiated the request. When requests pass through multiple proxies or load balancers, each proxy adds its own IP address to the X-Forwarded-For header. Azure App Services can use this header to determine the original client IP address, even if the request came through intermediate proxies. Specifying the CIDR for IP ranges in a comma separated string works in most deployments to match the clients with the requests and allow them selectively through the gateway’s firehose traffic.

Together with source ip restrictions, these headers enable sufficient hardening to the web traffic at the app service.


Tuesday, April 23, 2024

 This is a continuation of previous articles on IaC shortcomings and resolutions. While IaC code can be used deterministically to repeatedly create, update, and delete cloud resources, there are some dependencies that are managed by the resources themselves and become a concern for the end user when they are not properly cleaned up. Take for instance, the load balancers that compute instances and clusters create when they are provisioned using the Azure Machine Learning Workspaces. These are automatically provisioned. The purpose of this load balancer is to manage traffic even when the compute instance or cluster is stopped. Each compute instance has one load balancer associated with it, and for every 50 nodes in a compute cluster, one standard load balancer is billed. The load balancer ensures that requests are distributed evenly across the available compute resources, improving performance and availability. Each load balancer is billed at approximately $0.33 per day. If we have multiple compute instances, each one will have its own load balancer. For compute clusters, the load balancer cost is based on the total number of nodes in the cluster. One way to avoid load balancer costs on stopped compute instances and clusters, is to delete the compute resources when they are not in use. The IaC can help with the delete of the resources but whether the action is automated or manual, it is contingent on the delete of the load balancers and when delete fails for reasons such as locks on load balancers, then the user is left with a troublesome situation.

An understanding of the load balancer might help put things in perspective especially when trying to find them to unlock or delete. Many cloud resources and Azure Batch services create load balancers and the ways to distinguish them vary from resource groups, tags, or properties. These load balancers play a crucial role in distributing network traffic evenly across multiple compute resources to optimize performance and ensure high availability, they use various algorithms such as round-robin, least connections, or source IP affinity, to distribute incoming traffic to the available compute resources. This helps in maintaining a balanced workload and preventing any single resource from being overwhelmed. They also contribute to high availability by continuously monitoring the health of the compute resources. If a resource becomes unhealthy or unresponsive, the load balancer automatically redirects traffic to other healthy resources. They can seamlessly handle an increase in traffic by automatically scaling up the number of compute resources. Azure Machine Learning Workspace load balancers can scale up or down based on predefined rules or metrics, ensuring that the resources can handle the workload efficiently. Load balancing rules determine how traffic should be distributed. Rules can be configured based on protocols, ports, or other attributes to ensure that the traffic is routed correctly. Load balancers continuously monitor the health of the compute resources by sending health probes to check their responsiveness. If a resource fails the health probe, it is marked as unhealthy, and traffic is redirected to other healthy resources. Azure Machine Learning Workspace supports both internal and public load balancers. Internal load balancers are used for internal traffic within a virtual network, while public load balancers handle traffic from the internet. They can be seamlessly integrated with other Azure services, such as virtual networks, virtual machines, and container services, to build scalable and highly available machine learning solutions. Overall, load balancers in Azure Machine Learning Workspace play a critical role in optimizing performance, ensuring high availability, and handling increased traffic by evenly distributing it across multiple compute resources.

Creating the compute with node public ip set to false and disabling local auth can prevent load balancers from being created but if endpoints are involved, the Azure Batch Service will create them. Load balancers, public ip addresses and associated dependencies are created in the resource group of the virtual network and not the resource group of the machine learning workspace. Finding the load balancers and taking appropriate action on them can allow the compute resources to be cleaned up. This can be done on an ad hoc basis or scheduled basis.

Monday, April 22, 2024

 This is a continuation of a previous article on IaC shortcomings and resolutions. With regard to Azure Machine Learning Workspace, here is a sample request and response:

1. Go to https://learn.microsoft.com/en-us/rest/api/azureml/compute/create-or-update?view=rest-azureml-2023-10-01&tabs=HTTP#code-try-0 and signin with your secondary account:


Specify the following:

PUT https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.MachineLearningServices/workspaces/<ml-workspace-name>/computes/<compute-name>?api-version=2023-10-01

Authorization: Bearer <automatically created access token>

Content-type: application/json

{

  "properties": {

    "properties": {

      "vmSize": "STANDARD_DS11_V2",

      "subnet": {

        "id": "/subscriptions/<subscription-id>/resourceGroups/<rg-vnet-name>/providers/Microsoft.Network/virtualNetworks/<vnet-name>/subnets/<subnet-name>"

      },

      "applicationSharingPolicy": "Shared",

      "computeInstanceAuthorizationType": "personal",

      "enableNodePublicIp": false,

      "disableLocalAuth": true,

      "location": "centralus",

      "scaleSettings": {

        "maxNodeCount": 1,

        "minNodeCount": 0,

        "nodeIdleTimeBeforeScaleDown": "PT60M"

      }

    },

    "computeType": "AmlCompute",

    "disableLocalAuth": true

  },

  "location": "centralus",

  "disableLocalAuth": true

}



2. Check the response code to match as shown:

Response Code: 201

azure-asyncoperation: https://management.azure.com/subscriptions/<subscription-id>/providers/Microsoft.MachineLearningServices/locations/centralus/computeOperationsStatus/f6dcbe07-99cf-4bf7-aa71-0fdcfc542941?api-version=2023-10-01&service=new

cache-control: no-cache

content-length: 1483

content-type: application/json; charset=utf-8

date: Sat, 20 Apr 2024 02:28:50 GMT

expires: -1

pragma: no-cache

request-context: appId=cid-v1:2d2e8e63-272e-4b3c-8598-4ee570a0e70d

strict-transport-security: max-age=31536000; includeSubDomains

x-aml-cluster: vienna-centralus-02

x-content-type-options: nosniff

x-ms-correlation-request-id: f15d6510-5d21-426a-98e5-aa800322da83

x-ms-ratelimit-remaining-subscription-writes: 1199

x-ms-request-id: f15d6510-5d21-426a-98e5-aa800322da83

x-ms-response-type: standard

x-ms-routing-request-id: NORTHCENTRALUS:20240420T022850Z:f15d6510-5d21-426a-98e5-aa800322da83

x-request-time: 0.257


Sunday, April 21, 2024

 Given clock hands positions for different points of time as pairs A[I][0] and A[I][1] where the order of the hands does not matter but their angle enclosed, count the number of pairs of points of time where the angles are the same

    public static int[] getClockHandsDelta(int[][] A) {

        int[] angles = new int[A.length];

        for (int i = 0; i < A.length; i++){

            angles[i] = Math.max(A[i][0], A[i][1]) - Math.min(A[i][0],A[i][1]);

        }

        return angles;

    }

    public static int NChooseK(int n, int k)

    {

        if (k < 0 || k > n || n == 0) return 0;

        if ( k == 0 || k == n) return 1;

        return Factorial(n) / (Factorial(n-k) * Factorial(k));

    }

 

    public static int Factorial(int n) {

        if (n <= 1) return 1;

        return n * Factorial(n-1);

    }


    public static int countPairsWithIdenticalAnglesDelta(int[] angles){

        Arrays.sort(angles);

        int count = 1;

        int result = 0;

        for (int i = 1; i < angles.length; i++) {

            if (angles[i] == angles[i-1]) {

                count += 1;

            } else {

                if (count > 0) {

                    result += NChooseK(count, 2);

                }

                count = 1;

            }

        }

        if (count > 0) {

            result += NChooseK(count, 2);

            count = 0;

        }

        return result;

    }


        int [][] A = new int[5][2];

         A[0][0] = 1;    A[0][1] = 2;

         A[1][0] = 2;    A[1][1] = 4;

         A[2][0] = 4;    A[2][1] = 3;

         A[3][0] = 2;    A[3][1] = 3;

         A[4][0] = 1;    A[4][1] = 3;

 1 2 1 1 2 

1 1 1 2 2 

4


Saturday, April 20, 2024

 This is a continuation of previous articles on IaC shortcomings and resolutions. No infrastructure is useful without considerations for usability. As with the earlier example of using Azure Machine Learning workspace to train models using Snowflake data source, some consideration must be given to allow connections to data source and importing data. We cited resolving versions between Spark, Scala and Snowflake libraries within the kernel to allow data to be imported into a dataframe for use with SQL and this could be difficult for end-users if they were to locate the jars and download themselves. While the infrastructure could provide pre-configured kernels such as Almond kernel with appropriate jars such as for Scala, some samples might ease the task for datascientists wrangling with Snowflake data on existing workspaces.

For example, they could stage their action in multiple steps with pulling the data from snowflake and then loading it into a dataframe.

This is a sample code to do so:

from pyspark.sql import SparkSession

from pyspark.sql.types import StructType, StructField, StringType


spark = SparkSession.builder.appName("BytesToDataFrame").getOrCreate()


# Sample raw bytes (replace with your actual data from Snowflake using snowflake-connector cursor)

# https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example

# either using 

# a)               df = pd.DataFrame(cursor.fetchall())

# or

# b)               df = cursor.fetch_pandas_all()

# or

# c)


raw_bytes = [b'\xba\xed\x85\x8e\x91\xd4\xc7\xb0', b'\xba\xed\x85\x8e\x91\xd4\xc7\xb1']

schema = StructType([StructField("id", StringType(), True)])

rdd = spark.sparkContext.parallelize(raw_bytes)

df = spark.createDataFrame(rdd, schema=schema)

df.show()


In this example, the data is retrieved first with a cursor and then loaded into a dataframe.


Friday, April 19, 2024

 

This is a continuation of previous articles on allowing Spark/Scala/Snowflake code to execute on Azure Machine Learning Compute. The built-in Jupyter kernel of “Azure ML – Python 3.8” does not have pyspark and we discussed the choices of downloading version compatible jars as well as alternative code to get data from Snowflake.

In this article, we will review the steps to set up a Jupyter notebook for Snowpark Scala. An “Almond” kernel can be used to setup Scala and coursier can be used to install the Almond Kernel to specify a supported version of Scala. The Almond Kernel has a prerequisite that a Java Virtual Machine needs to be installed on the system. This can be done by installing AdoptOpenJDK version 8. Then Almond can be fetched with coursier, by downloading its release and running the executable with the command line parameters to install Almond and Scala. Coursier is a Scala application that makes it easy to manage artifacts. It can setup the Scala development environment by downloading and caching artifacts from the web.

The Jupyter notebook for Snowpark can then be configured by defining a variable for the path and directory for classes generated by the Scala REPL and creating it. The Scala REPL generates classes for the Scala code that user writes. This process of configuring the compiler is not complete without adding the directory created earlier as a dependency of the REPL interpreter. Next we create a new session in SnowPark with an example as below:

import $ivy.`com.snowflake:snowpark:1.12.0`

import com.snowflake.snowpark._

import com.snowflake.snowpark.functions._

val session = Session.builder.configs(Map(

    "URL" -> "https://<account_identifier>.snowflakecomputing.com",

    "USER" -> "<username>",

    "PASSWORD" -> "<password>",

    "ROLE" -> "<role_name>",

    "WAREHOUSE" -> "<warehouse_name>",

    "DB" -> "<database_name>",

    "SCHEMA" -> "<schema_name>"

)).create

session.addDependency(replClassPath)

and then the Ammonite Kernel classes can be added for the code.

The session can be used to run a SQL query and populate a dataframe which can then be used independent of the data source.

Previous articles: IaCResolutionsPart107.docx