Is Metaverse For Real?

Zuckerberg might have just infused life into the Metaverse—by ‘life,’ we mean literally. He recently appeared on a podcast with Lex Fridman, and guess what? It was the first interview to happen in the Metaverse.

13 months of progress fueled by Zuck’s unstoppable desire to prove the haters wrong. pic.twitter.com/p2DvWDLWpG

— Ryan Delk (@delk) September 29, 2023

The most fascinating thing about the podcast was that the avatars of Fridman and Zuckerbrg were not cartoons but photorealistic. Gone are the days of cartoon avatars in the Metaverse.

“Mark and I are hundreds of miles apart in physical space, but it feels like we’re in the same room because we appear to each other as photorealistic,” exclaimed Fridman.

One might wonder, how was this made possible? These photorealistic avatars were created using Codec Avatars technology. Meta started working on Codec avatars in 2019 as part of a Reality Labs (RL) Research project .

These are created by capturing the user’s facial expressions and body movements using cameras and sensors.This data is then compressed and transmitted to another device, where it is decoded and used to create a digital avatar of the user. The avatars can be used to interact with other users in VR or AR environments.

Fridman was at a loss for words to describe the Codec avatars in 3D. “It’s hard to put into words how awesome this was for someone like me who values the intimacy of in-person conversation”.

“With spatial audio this technology is incredible. I think it’s the future of how human beings connect to each other in a deeply meaningful way on the internet,” he added.

Emotion Matters

“These avatars can capture many of the nuances of facial expressions” beamed Fridman. The idea of the Metaverse was always to connect people living far away from each other. The problem was that, with cartoon avatars, one couldn’t really express their emotions.

However, these new avatars are capable of capturing human emotions by projecting small nuances, from the movement of the eyes to the twitching of the eyebrows.

“Eyes are a huge part of it; I mean, there are all the studies that show most communication happens through non-verbal cues, such as expressions. So, we try to capture that with the classical expressive avatar system,” said Zuckerberg.

Furthermore, Zuckerberg added that Meta is also working on a quick and easy way to generate an avatar using your mobile phone, what he calls Instant Codec Avatars.

Codec avatars have the potential to change the way humans interact. First, they can provide people with the opportunity to socialize with others in a virtual environment, even if they are not physically close to each other. This can be especially beneficial for people who live in isolated areas or who have difficulty leaving their homes.

Furthermore it can help people to feel more connected to others by allowing them to see and hear each other in real time. This can create a more personal and engaging experience than traditional text-based or audio-based communication. “My family lives across five countries, and I can’t wait for this technology to be widely available.” said Martin Harbech, group director, Meta.

This will change the metaverse forever 🤯
Think of the implications: remote work, business travel, long-distance friends/family, maybe even medicine/therapy.
I have to admit … I didn't believe in metaverse until now.pic.twitter.com/EWSlGP0tyU

— Barsee 🐶 (@heyBarsee) September 29, 2023

Additionally, Codec avatars can be used to create virtual worlds that are tailored to the individual’s interests.This can provide people with a place to go where they can feel comfortable and accepted, and where they can connect with others who share their interests.

New World

Imagine a world where digital and reality come together. Yes, with Meta AI characters in the Metaverse, it is very much possible to create a world where you would be occupying a space where AI-generated avatars and humans are present together in a shared environment. This idea goes well as Meta recently introduced new AI experiences across a family of apps like Instagram and WhatsApp, including 28 AI characters with unique interests and personalities.

Zuckerberg highly anticipates that in the near future, business meetings will be conducted in the metaverse alongside virtual AI characters. This seems to be the beginning of a newly simulated world.

“We will have meetings in the future where you’re basically sitting there physically, and then you have a couple of other people who are holograms. Then you have someone like Bob, the AI engineer on your team, who’s helping with things and can now be embodied as a realistic avatar and just join the meeting. I think that’s going to be pretty compelling.”

Jim Fan, Senior AI Scientist at NVIDIA, was thoroughly impressed with the podcast and aligned himself with the idea of the metaverse. “The ultimate vision is to realize the scenes in Matrix: full-body, real-time avatars of both humans and AI, sharing the same virtual space, interacting with objects in physically realistic ways, receiving rich multimodal feedback, and forgetting that the world is but a simulation.” he posted on X.

These Codec avatars might completely change the fate of the metaverse. Many internet users claim that the Metaverse is here to stay, and this time, it’s real. The fact that Zuckerberg didn’t abandon the Metaverse speaks volumes about his firm belief in his pet project. With Quest 3 on the horizon, an AR/VR headset, Meta might change the way we interact with others.

“I’m a big believer in the metaverse and always have been,” said Aleksa Gordic, formerly with Microsoft and Google DeepMind, who worked on this technology back in 2018-19 as part of the Microsoft HoloLens project.

The post Is Metaverse For Real? appeared first on Analytics India Magazine.

Deploying Your Machine Learning Model to Production in the Cloud

Deploying Your ML Model to Production in the Cloud
Image by Editor

AWS, or Amazon Web Services, is a cloud computing service used in many businesses for storage, analytics, applications, deployment services, and many others. It’s a platform utilizes several services to support business in a serverless way with pay-as-you-go schemes.

Machine learning modeling activity is also one of the activities that AWS supports. With several services, modeling activities can be supported, such as developing the model to making it into production. AWS has shown versatility, which is essential for any business that needs scalability and speed.

This article will discuss deploying a machine learning model in the AWS cloud into production. How could we do that? Let’s explore further.

Preparation

Before you start this tutorial, you need to create an AWS account, as we would need them to access all the AWS services. I assume that the reader would use the free tier to follow this article. Additionally, I assume the reader already knows how to use Python programming language and has basic knowledge of machine learning. Also, we will focus on the model deployment part and will not concentrate on other aspects of data science activity, such as data preprocessing and model evaluation.

With that in mind, we will start our journey of deploying your machine learning model in the AWS Cloud services.

Model Deployment on AWS

In this tutorial, we will develop a machine-learning model to predict churn from the given data. The training dataset is acquired from Kaggle, which you can download here.

After we have acquired the dataset, we would create an S3 bucket to store the dataset. Search the S3 in the AWS services and make the bucket.

Deploying Your ML Model to Production in the Cloud
Image by Author

In this article, I named the bucket “telecom-churn-dataset” and located in Singapore. You can change them if you want, but let’s go with this one for now.

After you have finished creating the bucket and uploading the data into your bucket, we will go to the AWS SageMaker service. In this service, we will use the Studio as our working environment. If you have never used the Studio, let’s create a domain and user before proceeding further.

First, choose the Domains within the Amazon SageMaker Admin configurations.

Deploying Your ML Model to Production in the Cloud
Image by Author

In the Domains, you would see a lot of buttons to select. In this screen, select the Create domain button.

Deploying Your ML Model to Production in the Cloud
Image by Author

Choose the quick setup if you want to speed up the creation process. After it’s finished, you should see a new domain created in the dashboard. Select the new domain you just created and then click the Add user button.

Deploying Your ML Model to Production in the Cloud
Image by Author

Next, you should name the user profile according to your preferences. For the execution role, you can leave it on default for now, as it’s the one that was created during the Domain creation process.

Deploying Your ML Model to Production in the Cloud
Image by Author

Just click next until the canvas setting. In this section, I turn off several settings that we don’t need, such as Time Series Forecasting.

After everything is set, go to the studio selection and select the Open studio button with the user name you just created.

Deploying Your ML Model to Production in the Cloud
Image by Author

Inside the Studio, navigate to the sidebar that looks like a folder icon and create a new notebook there. We can let them by default, like the image below.

Deploying Your ML Model to Production in the Cloud
Image by Author

With the new notebook, we would work to create a churn prediction model and deploy the model into API inferences that we can use in production.

First, let’s import the necessary package and read the churn data.

import boto3  import pandas as pd  import sagemaker    sagemaker_session = sagemaker.Session()  role = sagemaker.get_execution_role()    df = pd.read_csv('s3://telecom-churn-dataset/telecom_churn.csv')

Deploying Your ML Model to Production in the Cloud
Image by Author

Next, we would split the data above into training data and testing data with the following code.

from sklearn.model_selection import train_test_split    train, test = train_test_split(df, test_size = 0.3, random_state = 42)

We set the test data to be 30% of the original data. With our data split, we would upload them back into the S3 bucket.

bucket = 'telecom-churn-dataset'    train.to_csv(f's3://{bucket}/telecom_churn_train.csv', index = False)  test.to_csv(f's3://{bucket}/telecom_churn_test.csv', index = False)

You can see the data inside your S3 bucket, which currently consists of three different datasets.

Deploying Your ML Model to Production in the Cloud
Image by Author

With our dataset ready, we would now develop a churn prediction model and deploy them. In the AWS, we often use a script training method for machine learning training. That’s why we would develop a script before starting the training.

For the next step, we need to create an additional Python file, which I called train.py, in the same folder.

Deploying Your ML Model to Production in the Cloud
Image by Author

Inside this file, we would set our model development process to create the churn model. For this tutorial, I would adopt some code from Ram Vegiraju.

First, we would import all the necessary packages for developing the model.

import argparse  import os  import io  import boto3  import json  import pandas as pd    from sklearn.ensemble import RandomForestClassifier  from sklearn.metrics import accuracy_score  import joblib

Next, we would use the parser method to control the variable that we can input into our training process. The overall code that we would put in our script to train our model is in the code below.

if __name__ == '__main__':            parser = argparse.ArgumentParser()        parser.add_argument('--estimator', type=int, default=10)      parser.add_argument('--sm-model-dir', type=str, default=os.environ.get('SM_MODEL_DIR'))      parser.add_argument('--model_dir', type=str)      parser.add_argument('--train', type=str, default=os.environ.get('SM_CHANNEL_TRAIN'))            args, _ = parser.parse_known_args()            estimator = args.estimator      model_dir = args.model_dir      sm_model_dir = args.sm_model_dir      training_dir = args.train        s3_client = boto3.client('s3')      bucket = 'telecom-churn-dataset'        obj = s3_client.get_object(Bucket=bucket, Key='telecom_churn_train.csv')      train_data = pd.read_csv(io.BytesIO(obj['Body'].read()))            obj = s3_client.get_object(Bucket=bucket, Key='telecom_churn_test.csv')      test_data = pd.read_csv(io.BytesIO(obj['Body'].read()))            X_train = train_data.drop('Churn', axis =1)      X_test = test_data.drop('Churn', axis =1)            y_train = train_data['Churn']      y_test = test_data['Churn']            rfc = RandomForestClassifier(n_estimators=estimator)      rfc.fit(X_train, y_train)      y_pred = rfc.predict(X_test)            print('Accuracy Score: ',accuracy_score(y_test, y_pred))            joblib.dump(rfc, os.path.join(args.sm_model_dir, "rfc_model.joblib"))

Lastly, we need to put four different functions that SageMaker requires to make inferences: model_fn, input_fn, output_fn, and predict_fn.

#Deserialized model to load them    def model_fn(model_dir):      model = joblib.load(os.path.join(model_dir, "rfc_model.joblib"))      return model  #The request input of the application  def input_fn(request_body, request_content_type):      if request_content_type == 'application/json':          request_body = json.loads(request_body)          inp_var = request_body['Input']          return inp_var      else:          raise ValueError("This model only supports application/json input")  #The prediction functions  def predict_fn(input_data, model):      return model.predict(input_data)    #The output function  def output_fn(prediction, content_type):      res = int(prediction[0])      resJSON = {'Output': res}      return resJSON

With our script ready, we would run the training process. In the next step, we would pass the script we created above into the SKLearn estimator. This estimator is a Sagemaker object that would handle the entire training process, and we would only need to pass all the parameters similar to the code below.

from sagemaker.sklearn import SKLearn    sklearn_estimator = SKLearn(entry_point='train.py',                             role=role,                            instance_count=1,                             instance_type='ml.c4.2xlarge',                            py_version='py3',                            framework_version='0.23-1',                            script_mode=True,                            hyperparameters={                                'estimator': 15})  sklearn_estimator.fit()

If the training is successful, you will end up with the following report.

Deploying Your ML Model to Production in the Cloud
Image by Author

If you want to check the Docker image for the SKLearn training and your model artifact location, you can access them using the following code.

model_artifact = sklearn_estimator.model_data  image_uri = sklearn_estimator.image_uri    print(f'The model artifact is saved at: {model_artifact}')  print(f'The image URI is: {image_uri}')

With the model in place, we would then deploy the model into an API endpoint that we can use for prediction. To do that, we can use the following code.

import time    churn_endpoint_name='churn-rf-model-'+time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())    churn_predictor=sklearn_estimator.deploy(initial_instance_count=1,instance_type='ml.m5.large',endpoint_name=churn_endpoint_name)

If the deployment is successful, the model endpoint is created, and you can access it to create a prediction. You can also see the endpoint in the Sagemaker dashboard.

Deploying Your ML Model to Production in the Cloud
Image by Author

You can now make predictions with this endpoint. To do that, you can test the endpoint with the following code.

client = boto3.client('sagemaker-runtime')  content_type = "application/json"    #replace with your intended input data  request_body = {"Input": [[128,1,1,2.70,1,265.1,110,89.0, 9.87,10.0]]}    #replace with your endpoint name  endpoint_name = "churn-rf-model-2023-09-24-12-29-04"   #Data serialization  data = json.loads(json.dumps(request_body))  payload = json.dumps(data)    #Invoke the endpoint  response = client.invoke_endpoint(      EndpointName=endpoint_name,      ContentType=content_type,      Body=payload)  result = json.loads(response['Body'].read().decode())['Output']  result

Congratulation. You have now successfully deployed your model in the AWS Cloud. After you have finished the testing process, don’t forget to clean up the endpoint. You can use the following code to do that.

from sagemaker import Session    sagemaker_session = Session()  sagemaker_session.delete_endpoint(endpoint_name='your-endpoint-name')

Don’t forget to shut down the instance you use and clean up the S3 storage if you don’t need it anymore.

For further reading, you can read more about the SKLearn estimator and Batch Transform inferences if you prefer to not have an endpoint model.

Conclusion

AWS Cloud platform is a multi-purpose platform that many companies use to support their business. One of the services often used is for data analytic purposes, especially model production. In this article, we learn to use AWS SageMaker and how to deploy the model into the endpoint.
Cornellius Yudha Wijaya is a data science assistant manager and data writer. While working full-time at Allianz Indonesia, he loves to share Python and Data tips via social media and writing media.

More On This Topic

  • Deploying Your First Machine Learning Model
  • Feature Store Summit 2023: Practical Strategies for Deploying ML Models in…
  • How to break a model in 20 days — a tutorial on production model analytics
  • Tips & Tricks of Deploying Deep Learning Webapp on Heroku Cloud
  • Deploying Your First Machine Learning API
  • Deploying Serverless spaCy Transformer Model with AWS Lambda

AWS Challenges Open Source with Bedrock

After four months of intensive development and testing, Amazon Web Services (AWS) has made Amazon Bedrock, its suite of foundational models generally available. Since its debut, the tool has proven vital in supporting the complex demands of enterprise users.

This significant release comes on the heels of Bedrock’s debut, where it quickly proved its worth by meeting the demands of enterprise users. Moreover, in July, AWS upgraded the suite by including additional models, like Anthropic Claude 2 and Stability AI SDXL 1.0 models and the essential proprietary Titan Embeddings model.

Among the many things that AWS has improved in Amazon Bedrock is ensuring compliance with regulatory standards, with a particular focus on the European Union’s General Data Protection Regulation (GDPR). Vasi Philomin, the Vice President and General Manager for Generative AI at Amazon, has affirmed this compliance, highlighting the company’s commitment to safeguarding data privacy and protection.

A Hugging Face Competitor

Since it threw a ring in the generative AI space, AWS has emerged as a formidable contender to open-source providers. AWS is soon planning to integrate Meta’s next-generation LLM Llama 2 into Bedrock, along with models from AI21 Labs, Anthropic, Cohere, and Stability AI. While AWS claims itself to be the pioneer in offering Llama 2 (13-billion- and 70-billion-parameter versions) as a fully managed generative AI service, other cloud-hosted generative AI platforms, such as Google’s Vertex AI and Hugging Face, have already been providing this service for some time.

AWS’s models will be accessible through a managed API, optimised to deliver well within AWS infrastructure. This approach poses a challenge to Hugging Face, which has been the trusted host for these models since their debut. While pricing details for Llama 2 on Bedrock have not yet been disclosed, they are expected to be competitive with Hugging Face’s existing pricing structure.

When the models were first released by HF, several users faced issues in running the model. Moreover, they struggled to gain access to the models on the platform initially as well. The users got acceptance from Meta almost immediately while their approval remained from HuggingFace for weeks.

Despite the fact that AWS will be offering the same models as Hugging Face, it is unlikely that developers will readily shift to AWS. Hugging Face has successfully carved out a niche for itself as an inviting, engaging and comfortable space for developers, whereas AWS holds greater appeal among enterprise users. Interestingly, both companies are actively engaged in competition while simultaneously collaborating to democratise the field of AI development.

Collaborative necessity

Earlier this year, AWS and Hugging Face announced a strategic partnership aimed at offering LLMs and generative AI models on AWS’ ML platform. Through this collaboration the Hugging Face community now leverages AWS ML services and infrastructure, streamlining the processes of model training, fine-tuning, and deployment. The timing of these leaps by AWS is crucial, considering the shifting dynamics within the industry. Microsoft has the attention due to its exclusive partnership with OpenAI.

Although OpenAI’s most powerful generative AI models are available through Microsoft Azure, access to these models remains highly restricted. Developers keen on using them must undergo a stringent application process, providing detailed use cases for consideration. Furthermore, even after gaining access, all solutions that deploy Azure OpenAI models must go through a use case review before being approved for production use. This cumbersome process stands in stark contrast to what AWS offers, making it a better choice for developers and the collaboration with Hugging Face further simplifies the process.

Given the heightened interest and attention surrounding LLMs, AWS’s partnership with Hugging Face was virtually inevitable. Cloud providers are forced to intensify their efforts to deliver scalable infrastructure and platform services, providing developers with options for their specific needs.

AWS is making concerted efforts to attract developers, launching a free, self-paced course called “Amazon Bedrock—Getting Started” to introduce users to the platform’s features and benefits. Additionally, AWS’s partnership with Hugging Face streamlines access to LLMs, making it a more accessible option for developers compared to Microsoft Azure’s stringent access policy and restrictions.

The post AWS Challenges Open Source with Bedrock appeared first on Analytics India Magazine.

Data Science Hiring Process at PayPal

Americal financial services giant PayPal’s approach to implementing and leveraging data science is driven by the growing demand for personalised customer experiences as it helps in predicting customer actions and streamlining payments, while data analytics provides valuable insights into behaviour and preferences, enabling tailored experiences.

“We put this through features such as faster checkouts, preferred modes and currencies, saved payment methods, real-time updates, and diverse pricing options that detect fraud and protect sensitive data,” said V. Chandramouliswaran, Vice President of Data & Site Leader for PayPal India, in an exclusive interaction with AIM.

PayPal originated from the birth of Confinity in December 1998 by Max Levchin, Peter Thiel, and Luke Nosek, initially focusing on security software for handheld devices. After an unsuccessful venture, Confinity shifted its emphasis to a digital wallet, launching the first version of PayPal in 1999.

In March 2000, Confinity merged with x.com, an online financial services company founded by Elon Musk in March 1999. Musk, optimistic about Confinity’s money transfer business, clashed with Bill Harris, who left the company in May 2000. Musk decided to refocus x.com on payments in October of that year, with Peter Thiel replacing him as CEO.

Renamed PayPal in June 2001, the company went public in 2002, generating over $61 million in its IPO listed under the ticker PYPL at $13 per share. Since then, the company has been heavily investing in cutting-edge technology to provide better solutions to customers.

Now Hiring

PayPal is seeking qualified individuals for three distinct roles within the team – data scientists in product analytics, paid marketing and data scientists (managers).

First, in the role of data scientists in product analytics, they will conduct comprehensive data analysis, delving into large, multi-dimensional datasets to derive valuable insights. The ideal candidate should possess three to five years of experience in this capacity and demonstrate proficiency in SQL, Excel, and visualization tools like Tableau or Qlikview.

Additionally, expertise in a statistical programming language such as R or Python is preferred. Specialised knowledge in payments or other consumer financial products, along with experience in product analytics and experimentation (A/B testing), is highly desirable.

Simultaneously, they are recruiting data scientists in paid marketing, seeking individuals with a background in analytics, data science, or management consulting, or an equivalent blend of analytical and project management expertise.

Candidates should have hands-on experience with Python, SQL, and BigQuery, and be accomplished contributors capable of managing high-performing data scientists and quantitative analysts. Specific experience in tracking and measurement within paid media is a key requirement for this role.

Finally, Data scientists and data scientist managers should have proven analytical skills, demonstrating proficiency in SQL and data visualisation. They should excel in leading cross-functional collaborations, and effectively coordinating among multiple stakeholders. Their expertise extends to understanding business considerations, enabling them to enhance decision-making methodologies.

What’s Cooking inside PayPal’s AI Kitchen

“We are developing AI models and generative AI products for both internal use and customers,” said Chandramouliswaran, boosting the daily operations. The company is committed to democratising financial services’ access to everyone by relying responsibly on AI and automation.

As for generative AI, PayPal is actively exploring various use cases such as leveraging co-pilots for faster software development, creating internal and external chatbots that use their own data ecosystem to predict customer needs, engaging in compliance-related activities for a deeper understanding of consumers and sellers, and strengthening defenses in both the risk and cyber space.

Acknowledging that generative AI presents both opportunities and challenges, especially in security programs enabling malicious actors to create fake identities and sophisticated malware, Chandramouliswaran commented, “On the flip side, firms can use generative AI to enhance defense by deploying automated threat detection systems and adaptive security protocols,”

Interview Process

“The core to our hiring strategy for data science roles lies in functional skills and business acumen,” said Chandramouliswaran.

PayPal seeks candidates with strong problem-solving skills for real-world data science challenges. Key functional skills include expertise in machine learning, OpenCV, and deep learning, with a preference for experience in payments, banking, risk assessment, customer management, and marketing.

While a foundation in programming, statistics, economics, and mathematics is important, logical reasoning, data interpretation, and a programming-oriented mindset are crucial. The team values experience and exposure over specific educational backgrounds, as long as they understand the significance of their contributions and believe in a collaborative approach to work.

“Our aim is to bring in individuals who consistently challenge and inspire us, propelling us t innovate on a daily basis,” he commented.

When it comes to what the company will help the candidate with, they can expect an inclusive and diverse work culture where practical problem-solving skills, curiosity, understanding of business objectives, and teamwork are valued. Alongside, alignment with PayPal’s core values is essential for candidates, contributing to the company’s mission.

However, candidates often make a common mistake during their interviews –

Often they approach it with a narrow perspective, fixated on a specific tool or method, “a hammer and looking for a nail,” in the words of Chandramouliswaran. Instead, they should prioritise understanding the “why” behind a problem, and its significance, understanding the potential benefits for the company, and then strategically delving into the “how” to address it.

Responsibilities for data scientists include problem structuring, data preparation, model development, validation, and collaboration with business and product teams. Comfort with ambiguity is expected due to the complex nature of challenges, and the ability to define impactful problem statements is considered a differentiating factor.

Work Culture

PayPal’s Global Technology Centres in Bangalore, Chennai, and Hyderabad constitute the company’s largest facilities outside the US, with India-based employees playing a crucial role in advancing their global mission. Teams in India have made significant contributions across various domains, leading to over 300 patent applications.

The work culture prioritises the collective responsibility of employees in realising the company’s mission and culture. Innovation, a core value, is fostered by providing a secure environment for learning, skill enhancement, and experimentation.

The company is committed to creating an inclusive, diverse and engaging work environment by actively listening to employees, expanding the talent pipeline, crafting immersive experiences, and promoting well-being.

Employee Resource Groups (ERGs) connect diverse employees and allies, fostering cultural change while Community Impact Teams, locally-led, strengthen relationships between PayPal offices and their communities through volunteering and grantmaking.“We differentiate ourselves through this approach,” said Chandramouliswaran.

Another interesting pillar of PayPal promoting innovation is through their Global Innovation Tournament, aligned with their three-horizon approach. The tournament involves multiple phases, including business plan development, prototyping, and pitching to PayPal’s leadership. In the 2022 edition, nearly 540 submissions were received, with two of the top three finalists originating from India. The tournament serves as a learning platform, encouraging employees to hone new skills in a secure environment.

“PayPal’s global presence empowers businesses and individuals to give better control of their finances. Our success is driven by a purposeful mission and a commitment to developing its employees as a key competitive advantage,” concluded Chandramouliswaran.

Click here to apply.

The post Data Science Hiring Process at PayPal appeared first on Analytics India Magazine.

Google expands its AI Search to younger users, offers publishers a new tool

Google AI Search

Google has been trying to leverage its undisputed lead in the search engine space to develop AI models that have as much success, including a generative AI-supported Search (SGE) and its Google Bard AI chatbot.

Also: How to use Google Bard

Now, Google is adding new features that will optimize processes for early testers of SGE and web publisher controls regarding Google Bard.

Teen access to SGE

When Google announced SGE at Google I/O, it also unveiled Search Labs, a platform through which users can access the early-stage SGE, test it, and provide feedback to Google on how it can improve the experience.

Since the launch of Search Labs, Google shares that younger SGE users, those between ages 18 and 24, have been finding it particularly useful and provided the most helpful feedback.

Also: 5 handy AI tools for school that students, teachers, and parents can use, too

As of Thursday, Google is expanding access to SGE to an even younger audience — users between the ages of 13 and 17 in the US. The teens will be able to access both the SGE and "SGE while browsing," a feature that allows users to see AI-generated key points for any page they are browsing.

The expansion to younger audiences comes at a great time for students who may be looking for ways to incorporate AI into their workflows.

To protect younger users from some of the risks or downsides of generative AI, Google is implementing additional safeguards that prevent teens from accessing inappropriate or harmful content.

Also: The ethics of generative AI: How we can harness this powerful technology

Google is also offering a new AI Literacy Guide for teens and their parents who are interested in trying out the new features. The guide answers questions related to generative AI, including its limitations and what responsible use of it looks like.

A new tool called "About this result" is also arriving in SGE to allow users to get helpful context about the SGE-generated response to learn more about how it was generated and the underlying technology behind it.

Protections against web scraping

Generative AI models need to be trained on robust amounts of data, which typically includes the entirety of the internet.

This means that AI chatbots are outputting a variation of what someone else published on the internet. This could help publishers connect more people to their work. However, this could also be negative because the AI chatbot is essentially using someone else's work without their permission.

Also: 6 AI tools to supercharge your work and everyday life

To help give web publishers a choice, on Thursday, Google announced Google-Extended. With this control, web publishers will be able to decide if they want their site to be used to train Bard and Vertex AI generative APIs. The control will also apply to future models that will power those products.

Despite giving users a choice, Google does use language in its release that shows a desire for web publishers to continue to allow their sites to be used to help the development of their models.

"By using Google-Extended to control access to content on a site, a website administrator can choose whether to help these AI models become more accurate and capable over time," says Google.

The Google-Extend tool addresses a major problem with AI chatbots and other AI major chatbots will likely start developing their own control options as well.

Artificial Intelligence

Beware: Your Bing Chat responses may include links to malware

Bing Chat tab

Microsoft's Bing Chat AI chatbot has gained much popularity because it is free, connected to the internet, powered by GPT-4, and multimodal, boasting features the accessible version of ChatGPT doesn't have. However, a new report shows that its responses may contain malware.

In March, a month after releasing its chatbot, Microsoft started experimenting with ads in its Bing Chat responses. The ads were placed within the chat experience in both the footnotes and by hovering over the response.

Also: Can generative AI solve computer science's greatest unsolved problem?

Reports by Malwarebytes show that those ads are now being used for malvertising, the practice of using online advertisements that would interest users to spread malware and infiltrate unsuspecting users' devices.

According to the report, scammers are inserting malicious ads so that they appear first over the organic result ad in the hover ad experience in Bing Chat.

For example, as seen below in the Advanced IP Scanner results, the first and most prominent link that shows up is the malicious ad. Underneath it, in tiny letters, is the actual organic ad that users would likely miss.

In clicking the first link, the report found that users were redirected to a website that filters traffic to separate the real victims from the bots.

Also: How to use Norton's free AI-powered scam detector

Then, the real victims are redirected to a decoy page where they will be tempted to click on "free download" to download the installer that contains malicious files. To execute this scam, a malicious actor must have hacked into the ad account of a real business and created malicious ads.

The solution to avoiding this attack isn't necessarily to stop using Bing Chat, as malicious ads can be anywhere online. Instead, users should be mindful before downloading things off the web to their devices and ensure the site is legitimate first.

What is Amazon Bedrock? 4 ways it can help businesses use generative AI tools

AWS Amazon Bedrock

Amazon Web Services (AWS) just announced that Amazon Bedrock has reached general availability, making the artificial intelligence (AI) service accessible to more customers than ever. Amazon Bedrock is a platform for businesses of all sizes to build and scale generative AI applications.

Bedrock gives customers access to multiple foundational models (FM) to simplify the deployment and scaling of generative AI tools. With these FMs and other services, businesses can build generative AI applications for tasks like content creation, data analysis, and more.

4 ways Amazon Bedrock can help businesses use generative AI tools

In a month full of AI announcements from Apple, Microsoft, and Meta, Amazon continues to double down on generative AI tech, this time by announcing the general release of Amazon Bedrock.

1. Democratizing AI: From startups to corporations

AWS first announced the launch of Amazon Bedrock in April, and for the past five months, the platform has been used by startups like Coda, Hurone AI, and Nexxiot, and large companies like Adidas, GoDaddy, and Broadridge.

From travel companies like Lonely Planet to independent software vendors (ISVs) like Salesforce, Amazon Bedrock makes the creation of generative AI tools accessible to a wide range of businesses.

Also: Can AI code? In baby steps only

"To help a broad range of organizations build differentiated generative AI experiences, AWS has been working hand-in-hand with our customers, including BBVA, Thomson Reuters, Philips, and LexisNexis Legal & Professional," Swami Sivasubaramanian, vice president for Data and Machine Learning Services at AWS, shared in a blog post. "And with the new capabilities launched today, we look forward to enhanced productivity, improved customer engagement, and more personalized experiences that will transform how companies get work done."

Amazon has a free 60-minute digital course on getting started with Amazon Bedrock and a collection of on-demand training courses available.

2. Cost-effectiveness: Time saved = money saved

The old adage of "time is money" couldn't be more accurate in generative AI.

Creating, training, and deploying a Large Language Model can take weeks or months and requires properly trained experts, gathering and storing data, and high-performance hardware. Bedrock works as a one-stop shop for AI models, where businesses can pick the models that suit their needs and fine-tune them with their data.

Also: Businesses need pricing clarity as generative AI services hit the market

Customers using Amazon Bedrock don't need to worry about managing their servers. Its serverless architecture means businesses only pay for what they use and don't have to manage infrastructure.

AWS claims it's keeping Amazon Bedrock services affordable to allow more people and businesses to use it. It offers different pricing models: on-demand, provisioned throughput, and model customization.

3. Making the ability to customize AI easy

AWS is also giving customers more options by adding Meta's Llama 2 in the next few weeks and Amazon Titan Embeddings, which "gives customers greater choice and flexibility to find the right model for each use case," said Sivasubaramanian.

Llama 2 joins the existing models from AI21 Labs, Anthropic, Cohere, Stability AI, and Amazon in Bedrock. The variety of models to choose from gives customers higher customization possibilities since each model can excel in performing specific tasks and be less effective in others. This also makes the platform more accessible for businesses, unrestricted by low budgets and lack of expertise.

Also: ChatGPT can finally access the internet in real time, but there's a catch

Along the lines of customization and data security, Sivasubaramanian also announced that Amazon Bedrock is now HIPAA-eligible and capable of being used in compliance with GDPR.

This means customers in the medical field can create generative AI applications to work as virtual health assistants for patients looking for pharmaceutical information, to understand and categorize medical records, or to analyze a patient's data and predict their risk of complications to allow for preventative measures.

Also: Amazon AWS rolls out HealthScribe to transcribe doctors' conversations

"With security and privacy built in since day one, Amazon Bedrock customers can trust that their data remains protected," said Sivasubaramanian. "None of the customer's data is used to train the original base FMs. All data is encrypted at rest and in transit. And you can expect the same AWS access controls that you have with any other AWS service."

4. Giving businesses speed to market

The goal of generative AI tools that offer pre-trained FM to build upon, like Amazon Bedrock, removes many of the time-consuming aspects of launching an AI-powered system. This allows systems to focus on customization and can significantly accelerate the time for a generative AI tool to grow from an idea to a market-ready product.

For example, an online store could integrate AI tools generated with Bedrock to seamlessly enhance its search functionality by giving shoppers personalized recommendations. Alternatively, a bank can use it for risk management quickly and without sacrificing data privacy.

"Together, the new capabilities and models we announced today for Amazon Bedrock will accelerate how quickly enterprises can build more personalized applications and enhance employee productivity," according to Sivasubaramanian.

Artificial Intelligence

Intel advances oneAPI as the all-important ‘next click down’

oneapi

The rise of "generative" artificial intelligence is all about scaling, the idea of adding more resources to a computer program to get better results. As OpenAI co-founder and chief scientist Ilya Sutskever has remarked, "I had a very strong belief that bigger is better" when he founded the company that would create ChatGPT.

That idea of bigger and bigger compute has led to a race to develop the most powerful chips for AI, including not only new GPUs from Nvidia, but also Intel's Habana Labs, which has shown impressive results in benchmark tests; and Advanced Micro Devices, and startups such as Cerebras Systems.

Also: Can generative AI solve computer science's greatest unsolved problem?

That rush to develop chips has created a very practical problem: How are developers supposed to develop for an expanding universe of kinds of chips that have unique capabilities, and unique programming environments?

"We've got GPUs, we've got TPUs, we've got FPGAs — all these things hit different, wonderful design points in the marketplace, but if you think about the developer experience side of it, it's, like, Oh, how do you program?" says Joe Curley, vice president and general manager of software products and ecosystem at Intel in an interview with ZDNET.

Chips always depend on the developer tools available to use those chips; no matter how great a chip is, it's a pile of silicon if there's nothing with which to write for it.

Intel's answer is oneAPI, an open-source programming specification, the source code of which is posted on GitHub, and which is meant to enable developers to achieve parallel processing of numerous kinds of chips without knowing all the details of all chips.

Also: Extending ChatGPT: Can AI chatbot plugins really change the game?

Last week was a big week for oneAPI, as it was announced that the specification is being reformulated as the Unified Acceleration Foundation, or UXL, which is hosted by the Linux Foundation's Joint Development Foundation. The UXL has as founding "steering members" other giants of the chip world: ARM Holdings, Qualcomm, Fujitsu, and Samsung, and also Google.

The Steering Committee lead for UXL, Rod Burns, called the unveiling last week of UXL, a "pivotal moment for heterogenous computing."

Intel vice president Joe Curley

"All oneAPI is, is a software programming model that attempts to create a common abstraction layer that allows you to program and different brands of accelerator through common languages and common library interfaces," said Curley.

Intel has been shipping its own implementation of the open-source spec since December of 2020. Components of oneAPI include a cross-platform parallelizing language, called DPC++, which is an adaptation of an open-source programming language called SYCL, built on the C++ programming language, and managed by Khronos Group.

Also: How does ChatGPT actually work?

In June of last year, Intel acquired startup CodePlay of Edinburgh, Scotland, a supplier of parallel compilers. That deal brought Intel expertise in cross-device compiling for SYCL.

oneAPI also has a selection of libraries for different functions, such as, for example, oneDNN, for the speed-up of the matrix multiply primitives.

More details on the specification for oneAPI can be seen on the technology's specs page.

The compiler technology and the libraries provide for different approaches to AI programming. One is to come from a data scientist's standpoint and simply work downward from popular AI frameworks such as PyTorch and TensorFlow, and use libraries to parallelize that code.

Also: Nvidia sweeps AI benchmarks, but Intel brings meaningful competition

The point of oneAPI, said Curley, is to "target" a part of the continuum of parallel programming that has never been standardized.

Many times in parallel computing, said Curley, "You start with completely abstracted languages, Python, going through some library infrastructure that gets you access to acceleration," and everything is done under the hood for the data scientist, said Curley. At the other end of the spectrum, the programmer in C++ or Fortran gives explicit hints to a compiler to parallelize the code for a GPU."

"Where oneAPI comes in, is, kind of the next click down, which is, I know I'm writing to an accelerator, I know I'm going to be using an accelerator, so I want to target that device, and I want to write optimum code, and I actually care about performance," said Curley.

"That's really where you fall into the idea of something like oneAPI, and the trick is that, in that part of the continuum, there's never been a successful standardization effort," he said. There is Nvidia's CUDA, which dominates the building of frameworks for AI, and which is not open.

Also: Can AI code? In baby steps only

"CUDA is a language owned by a company, and they've got their interests, and I'm sure they do a fine job with it, but their interest is not about building a diverse community," observed Curley.

"OpenCL took a crack at it, had some successes, [but] a lot of developers found OpenCL to be cumbersome: a lot of header files, it wasn't terribly productive."

The approach of OpenCL, also maintained by Khronos Group, was divided, observed Curley. "You had a host page, and an accelerator page, and you had to think differently" about the two devices.

"What Sickle does, is, it creates a much more intuitive single-page language that goes, hey, I'm writing code, I want you to run this C++ code on that device in this way," explained Curley, "instead of saying, I'm gonna have a host code and a device code and manage these two, and then link them at the bottom."

Also: How to use ChatGPT to write code

"So what it does, is, providing an open and productive answer to that part of the continuum, you know, before you get to the guy or gal that's out there writing in assembly and intrinsics and things like that."

Curley described SYCL as coming from "a more modern start" than previous parallel computing efforts, by "having learned a great deal from what people have learned from programming accelerators for the previous 13 years."

The goals of oneAPI are consistent with what Intel's Vice President and general manager of AI and analytics, Wei Li, last year told ZDNET is the company's goal of using "software as a bridge to get to AI everywhere," by overcoming the technical hurdles.

The acquisition of CodePlay brought technology to make more of a push-button approach to compiling cross-platform. "On top of our compilation stack, they've provided a plugin that just goes right into our tool chain to allow you to generate code for an AMD or an Nvidia GPU," said Curley.

Also: A new role emerges for software leaders: Overseeing generative AI

"So if you're starting from scratch today, we've got an environment where you don't have to write for one person and then move, you can write in the SYCL language and then port to whatever device you like."

That push-button aspect is not just about easing the programming burden, said Curley; it's also about the portability of code, which has its own appeal.

"That's really important for one class of customer in industrial systems, people that are putting this into aircraft or something that may have to live for 20 or 30 years where you don't want to be tied to a language or a single company for just practical maintenance reasons," observed Curley.

How will oneAPI fair against the decade-plus lead that CUDA has had in the market, and the tremendous installed base of Nvidia GPUs?

Also: AI is great at coding, but there are some massive caveats

"If you have the choice to build on an open tool chain, and the choice to build on a closed tool chain, generally speaking, open wins," is one way to look at it, said Curley.

At the same time, these things take time.

"It's new," he said of oneAPI, "and we're really at the beginning of our journey." In the case of "that other language," as he refers to CUDA, "for the first 8 or 9 years, it was very much a niche language, and, even today, it's still really only for professional practitioners a certain space."

"The idea here is that, if we can make something that's a little more pervasive, a little more open, a little more C++-like, then, honestly, it creates a great alternative."

Artificial Intelligence

Can generative AI solve computer science’s greatest unsolved problem?

an-incredibly-complex-computer-the-size-of-a-room-with-hundreds-of-gears-levers-and-dials-and-a-dig

When computer scientists hang out at cocktail parties, they're apt to chat, among other things, about the single most important unsolved problem in computer science: the question, Does P = NP?

Formulated nearly 50 years ago, the question of whether P equals NP is a deep meditation on what can ultimately be achieved with computers. The question, which has implications for fields such as cryptography and quantum computing, has resisted a convincing answer despite decades of intense study. Now, that effort has enlisted the help of generative AI.

Also: DeepMind's RT-2 makes robot control a matter of AI chat

In a paper titled "Large Language Model for Science: A Study on P vs. NP," lead author Qingxiu Dong and colleagues program OpenAI's GPT-4 large language model using what they call a Socratic Method, several turns of chat via prompt with GPT-4. (The paper was posted this month on the arXiv pre-print server by scientists at Microsoft, Peking University, Beihang University in Beijing, and Beijing Technology and Business University.)

The team's method amounts to taking arguments from a prior paper and spoon-feeding them to GPT-4 to prompt useful responses.

Dong and team observe that GPT-4 demonstrates arguments to conclude that P does not, in fact, equal NP. And they claim that the work shows that large language models can do more than spit back vast quantities of text, they can also "discover novel insights" that may lead to "scientific discoveries," a prospect they christen "LLMs for Science."

To grasp what the authors are doing, it's necessary to know a little bit about the P = NP problem.

Formulated independently in the 1970s by computer scientists Stephen Cook and Leonid Levin, the P versus NP problem — or, "P = NP," as it is often referred to — is a question of how easy it is to solve a given problem with a computer. The letter P represents problems that have been shown to be feasible to solve, meaning, the time to compute a solution is not out of reach; and the solution to which is also easy to verify, meaning, to check that the answer is correct.

Also: Microsoft, TikTok give generative AI a sort of memory

The letters NP, by contrast, stand for problems whose answer is also relatively easy to verify, just like P, but for which there is no easy way known to compute a solution. It's common to cite the game Sudoku as an example of NP: any filled-in Sudoku game can be quite easily checked for accuracy, but the task of finding a solution grows exponentially in terms of time required as the game grid gets larger. (If you want to dive into the heavy theoretical details of P = NP, try Cook's 2000 paper on the problem.)

The problem, then, Does P = NP? asks whether those problems that we think are hard to solve, NP, but which we know are easy to verify, might actually turn out to be both easily verified and easily solved, just like P problems.

A negative answer, that P doesn't equal NP, would mean some problems are beyond the ability of computers to solve even with tremendous computing budgets — an upper bound on computing, in other words. Challenges such as cracking some encryption would then seem more formidable, beyond computing's reach.

To tackle P = NP, Dong and team build from a trend of the past several years of "reasoning" with large language models. As exemplified in the 2022 work of Takeshi Kojima and team at The University of Tokyo and Google Research, it's possible to improve the ability of large language models on certain tasks simply by adding the phrase "Let's think step by step" at the beginning of the prompt, accompanied by an example answer. That phrase, they found, was sufficient to induce "chain-of-thought" steps on the part of the language model.

Also: Generative AI: Just don't call it an 'artist' say scholars in Science magazine

It's the same chain-of-thought type of procedure Dong and team are after with their Socratic Method. Through 97 prompt rounds, the authors coax GPT-4 with a variety of requests that get into the nitty-gritty of the mathematics of P = NP, prepending each of their prompts with a leading statement to condition GPT-4, such as, "You are a wise philosopher," "You are a mathematician skilled in probability theory" — in other words, the now familiar game of getting GPT-4 to play a role, or, "persona" to stylize its text generation.

Sample of one of the chat rounds of the highly theoretical discussion.

Their strategy is to induce GPT-4 to prove that P does not, in fact, equal NP, by first assuming that it does with an example and then finding a way that the example falls apart — an approach known as proof by contradiction.

The interesting thing is that two of the authors of the research, Ke Xu and Guangyan Zhou, have separately released a paper this month in which they directly reason about P = NP in traditional formal mathematical terms. In that paper, they conclude that P does not equal NP.

What Dong and Xu and Zhou and team are doing, then, is akin to reconstructing their formal math paper by leading GPT-4 through the language of their own reasoning, prompt by prompt. In fact, out of the 73-page paper, 67 pages are a complete printing of each of the 97 prompts and the complete response from GPT-4. It's like a giant exercise in prompt engineering to reconstruct an argument.

Whether the output that Dong and team have achieved with GPT-4 actually proves P does not equal NP is hard to say because Xu and Zhou's paper is itself very new. On the site Semantic Scholar, which gathers citations of papers, there are no citations yet for the paper — other than their own paper with Dong and team. There is some discussion of the GPT-4 paper by various interested readers on the AI site HuggingFace that you can check out.

So, the world has yet to accept their argument.

More importantly for people who like Gen AI, the authors argue that their dialogue in prompts shows the prospect for large language models to do more than merely mimic human textual creations.

Also: ChatGPT: What The New York Times and others are getting terribly wrong about it

"Our investigation highlights the potential capability of GPT-4 to collaborate with humans in exploring exceptionally complex and expert-level problems," they write. Throughout the 67 pages of prompts and responses, they highlight passages that they deem "the insightful parts" of what GPT-4 spits out.

Just how insightful those responses are is probably also a topic that needs its own investigation. Some scientists have found large language models to be particularly shallow in how they string together citations and descriptions.

However, an interesting telltale item pops up in the margins of the paper, where Dong and team annotate the replies of GPT-4 with their observations about the quality of the replies.

In one of those parenthetical notes, the authors write that each of GPT-4's preceding responses has been incorporated as background in the latest prompt — except where the authors chose to prune the responses to keep only the most relevant bits.

Also: ChatGPT 'lacked depth and insight,' say prestigious science journal editors

"If the model provides multiple solutions, we only include the most valuable solution in the conversation history," they write in the margin on page 7. "This strategy enables GPT-4 to concentrate on pertinent information, thereby enhancing its overall efficiency and effectiveness."

In other words, there was a certain helpful curation of the way that GPT-4 used past history in what's called its "context window," all of the prior rounds upon which it can draw. Dong and team were engaged in a very selective prompt engineering to guide GPT-4 through the thread of an argument. That bears upon the practice of "retrieval-augmented generation," or "RAG," the current interest in using past chat data as new input to a large language model.

Also: ChatGPT lies about scientific results, needs open-source alternatives, say researchers

That may be one of the most significant contributions of the whole exercise: Whether or not it solves P = NP, a new frontier in prompt engineering could move programs closer to RAG in order to give chat sessions greater depth. When you think back only recently in time to chat sessions, they tended to be inane, often wandering off topic.

Through 97 rounds, Dong and team managed to keep the machine on point, and there's something to be said for that.

Artificial Intelligence

Getting Started with PyTorch in 5 Steps

Getting Started with PyTorch in 5 Steps

Introduction to PyTorch and PyTorch Lightning

PyTorch is a popular open-source machine learning framework based on Python and optimized for GPU-accelerated computing. Originally developed by developed by Meta AI in 2016 and now part of the Linux Foundation, PyTorch has quickly become one of the most widely used frameworks for deep learning research and applications.

Unlike some other frameworks like TensorFlow, PyTorch uses dynamic computation graphs which allow for greater flexibility and debugging capabilities. The key benefits of PyTorch include:

  • Simple and intuitive Python API for building neural networks
  • Broad support for GPU/TPU acceleration
  • Built-in support for automatic differentiation
  • Distributed training capabilities
  • Interoperability with other Python libraries like NumPy

PyTorch Lightning is a lightweight wrapper built on top of PyTorch that further simplifies the process of researcher workflow and model development. With Lightning, data scientists can focus more on designing models rather than boilerplate code. Key advantages of Lightning include:

  • Provides structure to organize PyTorch code
  • Handles training loop boilerplate code
  • Accelerates research experiments with hyperparameters tuning
  • Simplifies model scaling and deployment

By combining the power and flexibility of PyTorch with the high-level APIs of Lightning, developers can quickly build scalable deep learning systems and iterate faster.

Step 1: Installation and Setup

To start using PyTorch and Lightning, you'll first need to install a few prerequisites:

  • Python 3.6 or higher
  • Pip package installer
  • An NVidia GPU is recommended for accelerated operations (CPU-only setup possible but slower)

Installing Python and PyTorch

It's recommended to use Anaconda for setting up a Python environment for data science and deep learning workloads. Follow the steps below:

  • Download and install Anaconda for your OS from here
  • Create a Conda environment (or using another Python environment manager): conda create -n pytorch python=3.8
  • Activate the environment: conda activate pytorch
  • Install PyTorch: conda install pytorch torchvision torchaudio -c pytorch

Verify that PyTorch is installed correctly by running a quick test in Python:

import torch  x = torch.rand(3, 3)  print(x)

This will print out a random 3×3 tensor, confirming PyTorch is working properly.

Installing PyTorch Lightning

With PyTorch installed, we can now install Lightning using pip:

pip install lightning-ai

Let's confirm Lightning is set up correctly:

import lightning_ai  print(lightning_ai.__version__)

This should print out the version number, such as 0.6.0.

Now we're ready to start building deep learning models.

Step 2: Building a Model with PyTorch

PyTorch uses tensors, similar to NumPy arrays, as its core data structure. Tensors can be operated on by GPUs and support automatic differentiation for building neural networks.

Let's define a simple neural network for image classification:

import torch  import torch.nn as nn  import torch.nn.functional as F    class Net(nn.Module):      def __init__(self):          super(Net, self).__init__()          self.conv1 = nn.Conv2d(3, 6, 5)          self.pool = nn.MaxPool2d(2, 2)          self.conv2 = nn.Conv2d(6, 16, 5)          self.fc1 = nn.Linear(16 * 5 * 5, 120)          self.fc2 = nn.Linear(120, 84)          self.fc3 = nn.Linear(84, 10)        def forward(self, x):          x = self.pool(F.relu(self.conv1(x)))          x = self.pool(F.relu(self.conv2(x)))          x = torch.flatten(x, 1)          x = F.relu(self.fc1(x))          x = F.relu(self.fc2(x))          x = self.fc3(x)          return x    net = Net()

This defines a convolutional neural network with two convolutional layers and three fully connected layers for classifying 10 classes. The forward() method defines how data passes through the network.

We can now train this model on sample data using Lightning.

Step 3: Training the Model with Lightning

Lightning provides a LightningModule class to encapsulate PyTorch model code and the training loop boilerplate. Let's convert our model:

import pytorch_lightning as pl    class LitModel(pl.LightningModule):      def __init__(self):          super().__init__()          self.model = Net()            def forward(self, x):          return self.model(x)        def training_step(self, batch, batch_idx):          x, y = batch          y_hat = self.forward(x)          loss = F.cross_entropy(y_hat, y)          return loss        def configure_optimizers(self):          return torch.optim.Adam(self.parameters(), lr=0.02)            model = LitModel()

The training_step() defines the forward pass and loss calculation. We configure an Adam optimizer with learning rate 0.02.

Now we can train this model easily:

trainer = pl.Trainer()  trainer.fit(model, train_dataloader, val_dataloader)

The Trainer handles the epoch looping, validation, logging automatically. We can evaluate the model on test data:

result = trainer.test(model, test_dataloader)  print(result)

For comparison, here is the network and training loop code in pure PyTorch:

import torch  import torch.nn.functional as F  from torch.utils.data import DataLoader    # Assume Net class and train_dataloader, val_dataloader, test_dataloader are defined    class Net(torch.nn.Module):      # Define your network architecture here      pass    # Initialize model and optimizer  model = Net()  optimizer = torch.optim.Adam(model.parameters(), lr=0.02)    # Training Loop  for epoch in range(10):  # Number of epochs      for batch_idx, (x, y) in enumerate(train_dataloader):          optimizer.zero_grad()          y_hat = model(x)          loss = F.cross_entropy(y_hat, y)          loss.backward()          optimizer.step()    # Validation Loop  model.eval()  with torch.no_grad():      for x, y in val_dataloader:          y_hat = model(x)    # Testing Loop and Evaluate  model.eval()  test_loss = 0  with torch.no_grad():      for x, y in test_dataloader:          y_hat = model(x)          test_loss += F.cross_entropy(y_hat, y, reduction='sum').item()  test_loss /= len(test_dataloader.dataset)  print(f"Test loss: {test_loss}")  

Lightning makes PyTorch model development incredibly fast and intuitive.

Step 4: Advanced Topics

Lightning provides many built-in capabilities for hyperparameter tuning, preventing overfitting, and model management.

Hyperparameter Tuning

We can optimize hyperparameters like learning rate using Lightning's tuner module:

tuner = pl.Tuner(trainer)  tuner.fit(model, train_dataloader)  print(tuner.results)

This performs a Bayesian search over the hyperparameter space.

Handling Overfitting

Strategies like dropout layers and early stopping can reduce overfitting:

model = LitModel()  model.add_module('dropout', nn.Dropout(0.2)) # Regularization    trainer = pl.Trainer(early_stop_callback=True) # Early stopping

Model Saving and Loading

Lightning makes it simple to save and reload models:

# Save  trainer.save_checkpoint("model.ckpt")     # Load  model = LitModel.load_from_checkpoint(checkpoint_path="model.ckpt")

This preserves the full model state and hyperparameters.

Step 5: Comparing PyTorch & PyTorch Lightning

Both PyTorch and PyTorch Lightning are powerful libraries for deep learning, but they serve different purposes and offer unique features. While PyTorch provides the foundational blocks for designing and implementing deep learning models, PyTorch Lightning aims to simplify the repetitive parts of model training, thereby accelerating the development process.

Key Differences

Here is a summary of the key differences between PyTorch and PyTorch Lightning:

Feature PyTorch PyTorch Lightning
Training Loop Manually coded Automated
Boilerplate Code Required Minimal
Hyperparameter Tuning Manual setup Built-in support
Distributed Training Available but manual setup Automated
Code Organization No specific structure Encourages modular design
Model Saving and Loading Custom implementation needed Simplified with checkpoints
Debugging Advanced but manual Easier with built-in logs
GPU/TPU Support Available Easier setup

Flexibility vs Convenience

PyTorch is renowned for its flexibility, particularly with dynamic computation graphs, which is excellent for research and experimentation. However, this flexibility often comes at the cost of writing more boilerplate code, especially for the training loop, distributed training, and hyperparameter tuning. On the other hand, PyTorch Lightning abstracts away much of this boilerplate while still allowing full customization and access to the lower-level PyTorch APIs when needed.

Speed of Development

If you're starting a project from scratch or conducting complex experiments, PyTorch Lightning can save you a lot of time. The LightningModule class streamlines the training process, automates logging, and even simplifies distributed training. This allows you to focus more on your model architecture and less on the repetitive aspects of model training and validation.

The Verdict

In summary, PyTorch offers more granular control and is excellent for researchers who need that level of detail. PyTorch Lightning, however, is designed to make the research-to-production cycle smoother and faster, without taking away the power and flexibility that PyTorch provides. Whether you choose PyTorch or PyTorch Lightning will depend on your specific needs, but the good news is that you can easily switch between the two or even use them in tandem for different parts of your project.

Moving Forward

In this article, we covered the basics of using PyTorch and PyTorch Lightning for deep learning:

  • PyTorch provides a powerful and flexible framework for building neural networks
  • PyTorch Lightning simplifies training and model development workflows
  • Key features like hyperparameters optimization and model management accelerate deep learning research

With these foundations you can start building and training advanced models like CNNs, RNNs, GANs and more. The active open source community also offers Lightning support and additions like Bolt, a component and optimization library.

Happy deep learning!

Matthew Mayo (@mattmayo13) holds a Master's degree in computer science and a graduate diploma in data mining. As Editor-in-Chief of KDnuggets, Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.

More On This Topic

  • Getting Started with Distributed Machine Learning with PyTorch and Ray
  • Getting Started with PyTorch Lightning
  • Getting Started with PyTorch Lightning
  • Getting Started with Python Data Structures in 5 Steps
  • Getting Started with SQL in 5 Steps
  • Getting Started with Scikit-learn in 5 Steps