<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Utkan Tolga Evren on Medium]]></title>
        <description><![CDATA[Stories by Utkan Tolga Evren on Medium]]></description>
        <link>https://medium.com/@utolgaevren?source=rss-715b2d3a673a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Utkan Tolga Evren on Medium</title>
            <link>https://medium.com/@utolgaevren?source=rss-715b2d3a673a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:29:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utolgaevren/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Does Artificial Intelligence Have a DNA?]]></title>
            <link>https://medium.com/@utolgaevren/does-artificial-intelligence-have-a-dna-bc9ce6bf2554?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc9ce6bf2554</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 10:12:51 GMT</pubDate>
            <atom:updated>2026-01-13T10:12:51.026Z</atom:updated>
            <content:encoded><![CDATA[<p>As we move from single-cell AI systems to multi-component systems, where do we write behavior?</p><p>We often talk about what artificial intelligence can do.<br>It writes text, generates code, suggests decisions, and sometimes even makes decisions.</p><p>But there is a question we ask far less often:</p><p><strong>How does a system behave?</strong></p><p>Can behavior be explained by information alone?<br>If two systems receive the same inputs, should we expect them to behave in the same way?</p><p>When it comes to humans, we answer these questions with a clear “no.”<br>Behavior is shaped not only by information, but by a combination of tendencies, constraints, experiences, and interactions.</p><p>So we are faced with a fundamental question:</p><p><strong>Where is behavior itself defined?</strong></p><p>Much of what we know about ourselves is based on observation.<br>We don’t have a user manual. We only see the outcome.</p><p>We have theories about the development of carbon-based life, yet humans remain extremely complex organisms. From single-cell life to multi-cellular forms, this diversity shares one common feature:<br>all of them have DNA — a kind of code.</p><p>The emergence of this code unfolded over very long time scales.</p><p><em>(The references to DNA, chromosomes, or single-cell and multi-cellular structures in this text are not meant as biological equivalents. They are design metaphors used to make it easier to think about behavioral structure and increasing complexity in AI systems. The goal is not to copy biology into artificial intelligence, but to make the question of where and how behavior is defined more visible.)</em></p><p>Today, we are experiencing a similar process in the silicon world — but in a highly accelerated form. I know that the phrase “silicon life” sounds exaggerated, but the analogy is useful in one sense:</p><p>Changes that took billions of years through natural processes are now happening within days or weeks in a large laboratory-like environment, shaped by the actions of thousands of developers.</p><p>The AI revolution that became visible in 2023 with ChatGPT has quietly turned all of us into daily users of artificial intelligence. But something even more interesting is happening at the same time:<br> every day, more AI creators, developers, and designers are emerging.</p><p>We are watching — like a fast-forwarded film — the kind of transformation that physical forces shaped on our planet over immense time scales.</p><p>And at this point, I can’t help but ask:</p><p><strong>Which stage of this process are we in?</strong></p><p>AI systems are becoming increasingly autonomous: they generate text, write code, prepare presentations, suggest decisions, and sometimes make decisions directly.</p><p>But how do they do this?</p><p>Human behavior cannot be explained by information alone. We do not expect two people with the same education and the same knowledge to behave in identical ways. Behavior emerges from a combination of internal tendencies, constraints, experiences, and environmental interactions.</p><p>So the core question returns:</p><p><strong>Where is behavior itself defined?</strong></p><p>In AI, the most practical answer today is “the prompt.”<br>We tend to assume that whatever we provide, the system simply executes.</p><p>But this answer is not sufficient.</p><p>I believe we are currently in a phase where we are coding the DNA of single-cell AI systems.</p><p>Systems designed for a single task, operating within a single context, with limited autonomy…<br>They resemble organisms that can function independently but cannot form complex structures.</p><p>At the same time, we are now building AI agents that solve problems by communicating with each other. These multi-agent systems resemble simple “cells” that, when working together, form a larger system.</p><p>Today, these cells come together, exchange information, and divide tasks.<br> Yet it is still difficult to speak of a shared, distinctive behavioral DNA.</p><p>I imagine that the next stage will bring more complex AI systems — systems with their own unique digital DNA.</p><p>In my view, we are currently in a transition period.<br>A phase of formation.</p><p>We are building the sensory organs of the silicon world: mathematics, statistics, probability, and computation.<br>AI systems “perceive” the world through these tools.</p><p>But there is still no fully formed system-level DNA.</p><p>We write code, train models, and produce executable systems.<br>Yet all of this increasingly feels like a lower layer.</p><p>At some point, these layers may become invisible.<br>It won’t feel like code is running — it will feel like <strong>something is behaving</strong>.</p><p>Just as with human DNA:<br>no one tracks which gene triggers which behavior in real time, yet the outcome is unmistakable.</p><p>The difference is that this time, this “DNA” is forming in our own laboratories, before our eyes, and largely through our own actions.</p><p>Whether we reach that point in six months or sixty years, I don’t know.</p><p>Perhaps this idea of a “DNA” will never fully materialize.<br>Perhaps I am looking at AI systems from the wrong angle.</p><p>But what I see today is this:<br>behavior is gradually becoming less tied to code, individual models, or isolated decisions.</p><p>I don’t know where this process will lead.<br>But I am watching it with genuine curiosity, eager to see where this line of thought might take us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc9ce6bf2554" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yapay Zekânın DNA’sı Var mı?]]></title>
            <link>https://medium.com/@utolgaevren/yapay-zek%C3%A2n%C4%B1n-dnas%C4%B1-var-m%C4%B1-9c4a889a22c2?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c4a889a22c2</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 10:01:51 GMT</pubDate>
            <atom:updated>2026-01-13T10:01:51.966Z</atom:updated>
            <content:encoded><![CDATA[<p>Yapay Zekânın DNA’sı Var mı?</p><p><em>Tek hücreli yapay zekâlardan çok hücreli sistemlere geçerken, davranışı nereye yazıyoruz?</em></p><p>Yapay zekâ hakkında çoğu zaman ne yapabildiğini konuşuyoruz.<br>Metin yazıyor, kod üretiyor, karar öneriyor, hatta kimi zaman karar veriyor.</p><p>Ama çok daha az sorduğumuz bir soru var:</p><p><strong>Bir sistem nasıl davranır?</strong></p><p>Davranış yalnızca bilgiyle açıklanabilir mi?<br>Aynı girdileri alan iki sistemin aynı şekilde davranmasını bekler miyiz?</p><p>İnsan söz konusu olduğunda bu sorulara net bir “hayır” cevabı veriyoruz.<br>Davranışı belirleyen şey yalnızca bilgi değil; eğilimler, sınırlar, deneyimler ve etkileşimlerin bileşimi.</p><p>O hâlde şu temel soruyla karşı karşıyayız:</p><p><strong>Davranışın kendisi nerede tanımlanıyor?</strong></p><p>Çünkü kendimizle ilgili bilgimiz büyük ölçüde <em>gözleme dayanıyor.</em><br>Elimizde bir kullanım kılavuzu yok. Sadece sonucu görüyoruz.</p><p>Karbon temelli canlı hayatın <strong>gelişimine dair</strong> teorilerimiz var ama insan, hâlâ son derece karmaşık bir organizma. Tek hücreliden çok hücreliye uzanan bu çeşitliliğin ortak bir noktası var:<br><strong>Hepsi bir DNA’ya, yani bir tür koda sahip.</strong></p><p>Bu kodun ortaya çıkışı çok uzun zaman ölçeklerine yayıldı.</p><p>(Burada kullandığım DNA, kromozom veya tek hücreli–çok hücreli benzetmeleri biyolojik birebirlik iddiası taşımıyor. Bunları, yapay zekâ sistemlerinin davranışsal yapısını ve evrimsel karmaşıklık artışını düşünmeyi kolaylaştıran <strong>tasarım metaforları</strong> olarak kullanıyorum. Amaç, biyolojiyi yapay zekâya kopyalamak değil; davranışın nerede ve nasıl tanımlandığını daha görünür hâle getirmek.)</p><p>Bugün ise benzer bir süreci, ama son derece hızlandırılmış bir biçimde, silikon dünyada yaşıyoruz. “Silikon canlı” ifadesinin abartılı olduğunu biliyorum; ama benzetme şu açıdan anlamlı:<br>Doğal süreçlerde milyarlarca yıl süren değişimler, bugün büyük bir laboratuvar ortamında, binlerce geliştiricinin müdahalesiyle günler ve haftalar içinde gerçekleşiyor.</p><p>2023’te ChatGPT ile görünür hâle gelen yapay zekâ devrimi, farkında olmadan hepimizi her gün daha fazla yapay zekâ kullanıcısı yaptı. Ama bundan daha ilginç olan başka bir şey var:<br><strong>Her gün daha fazla yapay zekâ üreticisi, geliştiricisi ve tasarımcısı ortaya çıkıyor.</strong></p><p>Gezegenimizi şekillendiren fiziksel kuvvetlerin uzun zaman ölçeklerinde yaptığı işi, silikon dünyada çok hızlı çekilmiş bir film gibi izliyoruz.</p><p>Ve bu noktada şu soruyu sormadan edemiyorum:<br><strong>Bu sürecin acaba hangi aşamasındayız?</strong></p><p>Yapay zekâ sistemleri giderek daha otonom hâle geliyor: metin üretiyor, kod yazıyor, sunum hazırlıyor, karar öneriyor ve kimi zaman doğrudan karar veriyor.</p><p>Peki bunu nasıl yapıyor?</p><p>İnsan davranışı yalnızca bilgiyle açıklanamaz. Aynı eğitimi alan, aynı bilgiye sahip iki kişinin aynı şekilde davranmasını beklemiyoruz. Davranışı belirleyen şey; içsel eğilimler, sınırlar, deneyimler ve çevresel etkileşimlerin bileşimi.</p><p>O zaman temel soru şu:<br><strong>Davranışın kendisi nerede tanımlanıyor?</strong></p><p>Yapay zekâ için bugün bu soruya verdiğimiz en pratik cevap “prompt”. Ne verdiysek, onu yapıyor gibi düşünüyoruz.</p><p>Ama bu cevap yeterli değil.</p><p>Bugün, tek hücreli yapay zekâların DNA’sını kodladığımız bir aşamada olduğumuzu düşünüyorum.</p><p>Tek bir görevi olan, tek bir bağlamda çalışan, sınırlı otonomiye sahip sistemler…<br>Bunlar, tek başına iş görebilen ama karmaşık yapılar oluşturamayan organizmalar gibi.</p><p>Buna karşılık artık <strong>birbirleriyle konuşarak iş çözen yapay zekâ agent’ları</strong> geliştiriyoruz. Multi-agent sistemler dediğimiz bu yapılar, tek tek ele alındığında basit görünen “hücrelerin”, birlikte çalışarak bir sistem oluşturmasına benziyor.</p><p>Bugün bu hücreler yan yana geliyor, konuşuyor, görev paylaşıyor.<br>Ama hâlâ ortak, ayırt edici bir <strong>davranışsal DNA</strong>’dan söz etmek zor.</p><p>Ben bir sonraki aşamada, daha karmaşık yapay zekâ sistemlerinin ortaya çıkacağını ve bu sistemlerin kendilerine özgü <strong>dijital DNA’larının</strong> oluşacağını hayal ediyorum.</p><p>Bana göre şu an bir geçiş dönemindeyiz.<br>Bir oluşum aşamasındayız.</p><p>Bugün silikon dünyanın duyu organlarını inşa ediyoruz. Matematik, istatistik, olasılık ve hesaplama…<br>Yapay zekâ sistemleri dünyayı bu araçlarla “algılıyor”.</p><p>Ama henüz ortada tam anlamıyla oluşmuş bir <strong>sistem DNA’sı</strong> yok.</p><p>Kod yazıyoruz, modeller eğitiyoruz, çalıştırılabilir sistemler üretiyoruz.<br>Ama bütün bunlar bana giderek daha fazla <strong>alt katman</strong> gibi gelmeye başlıyor.</p><p>Sanki bir noktadan sonra bu katmanlar görünmez olacak.<br>Kod çalışmıyor gibi değil de, <strong>bir şey davranıyormuş gibi</strong> hissedeceğiz.</p><p>Tıpkı insan DNA’sında olduğu gibi:<br>Kimse hangi genin hangi davranışı tetiklediğini anlık olarak takip etmez. Ama sonuç ortadadır.</p><p>Fark şu ki, bu kez bu “DNA” kendi laboratuvarlarımızda, gözümüzün önünde ve büyük ölçüde bizim tarafımızdan oluşuyor.</p><p>Bu noktaya altı ay sonra mı geliriz, altmış yıl sonra mı bilmiyorum.</p><p>Belki de bu “DNA” fikri hiç oluşmayacak.<br>Belki yapay zekâ sistemlerini anlamak için yanlış bir yerden bakıyorum.</p><p>Ama bugün gördüğüm şey şu:<br>Davranış giderek koddan, tekil modellerden ve tekil kararlardan bağımsızlaşan bir yapıya doğru ilerliyor.</p><p>Bu sürecin nereye gideceğini bilmiyorum.<br>Ama olan biteni heyecanla izliyor ve bu düşüncenin nereye varacağını görmek istiyorum.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c4a889a22c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce Einstein Analytics Studio ile AutoML]]></title>
            <link>https://medium.com/@utolgaevren/salesforce-einstein-analytics-studio-ile-automl-a78594c0f6a8?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a78594c0f6a8</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 20:55:17 GMT</pubDate>
            <atom:updated>2025-08-24T20:55:17.297Z</atom:updated>
            <content:encoded><![CDATA[<p>Veri bilimi; matematik, istatistik, mühendislik vb. farklı disiplinleri bir araya getiren, hem sonuca ulaşmanın hem de ulaşılan sonucu yorumlamanın karmaşık olabileceği bir alandır.<br> Özellikle <strong>generative AI</strong> (gen.ai) kullanımının giderek yaygınlaşmasıyla birlikte, veri bilimi konusunda da — verinin demokratikleşmesinde olduğu gibi — benzer bir süreci yaşadığımızı düşünüyorum.<br> Farklı alanlardaki birçok kişi, özellikle iş birimlerinde çalışan iş zekâsı uzmanları, artık veri bilimi çalışmalarını çok daha hızlı gerçekleştirebiliyor.<br> Bu yazıda, herhangi bir kodlama yapmaya gerek kalmadan, hızlı bir şekilde veri modelleme ve analitik model geliştirme imkânı sağlayan <strong>Salesforce Einstein Analytics Studio</strong> ile örnek bir veri seti kullanarak <strong>churn analizi</strong> yapacağım.</p><p>Öncelikle, gerçek olmayan, rastgele bir veri setini ChatGPT ile oluşturdum. Bu veri setinde şu kolonlar bulunmaktadır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*CsZPcPHXjk8shBkYL4kAXA.png" /><figcaption>Örnek Veri seti</figcaption></figure><p>Örnek veri seti, akaryakıt istasyonlarından alışveriş yapan son kullanıcılarla ilgili tamamen rastgele (random) oluşturulmuş veriler içermektedir.<br> Alanları seçerken, aylık ortalama istasyon ziyareti, sadakat programı üyeliği gibi davranışsal değişkenlerin yanı sıra, araç markası gibi demografik nitelikte değişkenlere de yer verdim.<br> Veri tamamen rastgele oluşturulduğu için, analiz sonuçlarının çok anlamlı olmasını beklemiyorum.<br> Ancak <strong>Einstein Analytics Studio</strong> kullanarak modelle ilgili birçok kontrolü hızlı ve zahmetsiz bir şekilde gerçekleştirebilmek, süreci oldukça verimli hâle getiriyor.<br> Şimdi adım adım devam edelim.</p><p>Öncelikle Einstein Analytics Studio’nun genel görünümüne bakalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MwFS2POsUXAzRR6uHcGuQ.png" /><figcaption>Einstein Anaytics Studio Genel Görünüm</figcaption></figure><h3><strong>Veri Yükleme</strong></h3><p>Einstein Analytics Studio’ya girdiğimizde sağ üst köşede yer alan create buttonunu kullanarak veriseti, model vb. yaratma işlemlerini yapıyoruz. Bu menüden dataseti seçerek veriyi yüklüyoruz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*D0-0P8O9nx-WNJVPyfgIKg.png" /><figcaption>Einstein Analytics Studio Yeni Veri Seti Oluşturma</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*0z4WPKCrA9dCLQ8oC-O9gA.png" /><figcaption>Einstein Analytics Studio Veri Seti Yükleme Ekranı</figcaption></figure><p>Veriyi yükledikten hemen sonra, verisetinin içeriğini hem ilgili boyutlarda kendimiz kolon seçerek , hem de yapmak istediğimizi metin olarak yazarak analiz edebiliyoruz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*SDerZM0BRiibqx5RvXzd-A.png" /><figcaption>Veri seti analiz örneği 1 — Mobil uygulama kullanımına göre dağılım</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*tW5xeDSHVkwMrouTscKmxQ.png" /><figcaption>Veri Seti Analiz Örneği 2 — Churn etme durumuna göre dağılım</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*dWOi417hcYEFfNglsNTRNA.png" /><figcaption>Veri Seti Analiz Örneği 3 — Araç markasına göre churn degerinin dağılımı</figcaption></figure><p>1000 satırlık örnek veri setini 700 churn eden , 300 churn etmeyen olacak şekilde belirledim. Einstein Analytics Studio’nun veri analizi menüsü içerisinde veriyi birçok farklı şekilde görselleştirmek mümkün. Bunun yanında tüm yapılan işlemleri bir tarihçe içerisinde görebiliyor olmakta, ayrıca çok güzel bir özellik. Bu yetkinlikleri kullanarak raporlama konusunda teknik yetkinliğe ihtiyaç duymadan, doğrudan temel veri analizi gerçekleştirilebiliyor. Veriyi yükledik, temel analizleri yaptık. Şimdi modelleme tarafına geçelim.</p><h3>Model Yaratma</h3><p>Einstein Analytics Studio’da veriyi yüklerken kullandığımız “create” buttonu kullanarak veya datasetin içerisinde “model create” buttonu basarak analitik model yaratıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*0Hk-xmSITF8xU6vB4Gvz4g.png" /><figcaption>Einstein Analytics Studio — Model Yaratma</figcaption></figure><p>Model yaratma tamamen sonuç odaklı olacak şekilde tasarlanmış. Öncelikle neyi tahminlemek istediğimizi veri setimizin kolonlarından seçiyoruz. Bizim örneğimiz churn edenleri tahmin etmek istiyor ve veri setimiz içerisinde churned(1:churn etmiş,0:churn etmemiş) alanı mevcut. churned alanını seçiyoruz. Bu seçimi yaptıktan sonra, bu tahminleme ile neyi hedeflediğimizi “So I can “ içerisinde minimize veya maximize olarak seçip , hangi değer üzerinden bu işlemi hedeflediğimizi belirtiyoruz. Örnekte maximize churned:0 seçtiğimizde, modelin churn etmeyenleri maximize etmesini istediğimizi belirtmiş olduk. Next diyerek bir sonraki adıma geçiyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*AM7R4REexhXNr2QSsKk2aQ.png" /><figcaption>Einstein Analytics Studio — Model Tanımlama</figcaption></figure><p>Bir sonraki menüde, model değişkenlerini otomatik tanımlama ( kararı Einstein Analytics Studio’ya bırakıyoruz) veya istersek kendimiz istediğimiz değişkenleri seçebiliyoruz. Otomatiği seçerek devam ediyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*GN3nS13VL9atRgrcLXSkNg.png" /><figcaption>Einstein Analytics Studio — Model Çalıştırma</figcaption></figure><p>Bu noktadan sonra Einstein Analytics Studio,modeli çalıştırıyor. Modeli çalıştırmak, modeli eğitmek, test etmek, kontrol etmek vb. veri bilimi geliştirme süreçlerinden oluşuyor. Model çalışması tamamlandığında, Einstein Analytics Studio, kullanıcıya hem modelle ilgili teknik değerlendirme raporlarını, hem de iş sonuçlarını çok detaylı şekilde sunuyor. Şimdi Einstein Analytics Studio’nun bir autoML aracı olarak sunduklarına detaylı bakalım.</p><h3>Model Sonuçlarını İnceleme</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*o4R3okJRM3WbymnKOO5Kvg.png" /><figcaption>Einstein Analytics Studio — Model Ana Sayfası</figcaption></figure><p>Model çalışması tamamlandıktan sonra, yukarıda gözüken sonuç sayfası açılıyor. Bu sayfanın sol tarafında model performansı( yukarıdaki resimde açık olan ekran) , model ayarları , tahminleme ve veri içgörüleri seçenekleri mevcut. Performans ile başlayalım</p><h3>Performans -&gt; Overview</h3><p>Modelin amacını özet olarak açıkladıktan sonra Einstein Analytics Studio modelin başarı kriterlerini belirtiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*YeQdA-ycGy5LH4pvZw7_7Q.png" /><figcaption>AUC Değerleri</figcaption></figure><h3>AUC</h3><p>İlk değerimiz AUC . Örnek datamız ile çalışan modelin AUC değeri 0.77. AUC kavramı, bir veri bilimci için zaten biliniyor ama veri bilimci olmayan fakat veriden model yaratarak değere ulaşmak isteyn bir kullanıcı bu değeri nasıl anlamlandırabilir? Einstein Analytics Studio, bu tür teknik kavramların hepsinin açıklamasını çok anlaşılır bir şekilde vermiş. Örneğin yukarıdaki görüntüde, AUC yazısının yanındaki ikona basınca AUC değerinin ne olduğu, ve hangi değerlerde olmasının beklendiği belirtilmiş:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*qzfo-qYSE0_w9ABjJo7vdA.png" /><figcaption>AUC Açıklaması</figcaption></figure><p>Açıklamadan anlıyoruz ki, bu kavram modelimizin ne kadar doğru sınıflandırma yaptığını belirtiyor. Eğer değerimiz 0.5&#39;ten küçükse, modelimiz rasgele tahmin eden bir model gibi çalışmış. 1&#39;e ne kadar yakınsa tahmin gücü o kadar yüksek. Ama 1 olursada veri ile ilgili bir problem olduğunu düşünmeliyiz.</p><p>Bence, veri bilimcisi olmayan ama veri bilimcisinin kullandığı yöntemleri hızlı bir şekilde kullanarak model çalıştırmak isteyen bir kullanıcı için Einstein Analytics Studio, çok açık ve anlaşılır bir çıktı sunuyor.</p><p>Gerçek olmayan veriden oluşturarak kullandığım bu analitik modelin AUC değeri 0.77. Açıklamada yazdıpı şekilde 0.5 ten büyük ama 1 de değil. Modelimin iyi sonuç verdiğini düşünebilirim. Devam edelim, başka ne değerlere bakmalıyım?</p><h3>Threshold</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*D6_Pd3eqG3mI3tkikb09cQ.png" /><figcaption>Threshold Değeri</figcaption></figure><p>Einstein Analytics Studio’nun bize gösterdiği 2.sonuç değeri “threshold”. Resimde görülen kırmızı ve yeşil bölümler ve onların ortasında yer alan 0.6996 değeri , modelin hangi olasılıkla churn etme kararını verdiğini belirtiyor. Model, hesaplamaları sonucunda, churn etme olasılığını 0.6996 ve yukarısı olarak hesaplarsa, müşteriyi churn etmiş, daha aşağıda hesaplarsa churn etmemiş olarak belirliyor. Bu değeri model detaylarında değiştirmek mümkün. Değeri değiştirmemiz durumunda ise, modelimizin karar verme konusunda daha esnek veya zorlayıcı olmasını sağlayabiliyoruz. Bu değeri yukseltirsek, modelimiz gerçekten churn edenleri bulmakta daha katı davranacak, azaltırsakta aslında churn etmeyenleri de churn etmiş gibi belirleyecek. Burada yaptığımız çalışmanın bir modelleme olduğunu, kesin sonuçlar elde etmeyi değil, gerçeğe en yakın sonuçlar elde etmeye çalıştıgımızı hatırlatmak istiyorum.</p><p><strong>“All models are wrong, but some are useful.”</strong><br> — <strong>George E. P. Box</strong></p><h3>Veri Kontrolü</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*UoYWO7xeA-hb5grWy0JaIQ.png" /><figcaption>Veri Kontrolü</figcaption></figure><p>Einstein Analytics Studio, “Asses Deployment Readiness” bölümünde, veri seti ile ilgili dikkat edilmesi gerekn bir durum, problem olup olmadığı hakkında da bilgi veriyor, eğer problem varsa ne yapılması gerektiği hakında da yol gösteriyor. enim kullandığım veri setinde 2 konu belirlenmiş. Bu bulgulardan bir tanesi “cross validation başarısız oldu” diyor. Yine bu terimi daha önce duymamış bir kullanıcı için, yeterli ve gerekli açıklama bulunuyor. Bu detaya ileride tekrar geleceğim. Özellikle yeterli ve gerekli açıklama diye belirtiyorum, terimin ne anlama geldiğini açıklamak gerekli, fakat tüm detaylarını bilmek gerekmiyor, o yüzden Einstein Analytics Studio, yeterli bir açıklamayla, modelin teknik tarafından çok iş çıktılarına odaklanmayı sağlayarak ilerlemeyi sağlıyor.</p><h3>Eğitim datası ve model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*MJE1KQFuTduireS5dImrQA.png" /><figcaption>Training data ve model</figcaption></figure><p>Aynı ekranın alt tarafında sol tarafta “Distribution of Outcome Variable” bölümünde, veri setinin içerisinde churn eden ve etmeyenlerin dağılımı gösteriliyor. Veri setinde 700 churn eden, 300 churn etmemiş müşteri yaratmıştık. Sağ tarafta ise “Top Predictors” bölümü altında , modelimizin churn etme/etmeme kararını vermede en etkili olan değişkenleri görüyoruz.</p><p>Eğer bu veri setini kendimiz inceleseydik, hem veriye bakarak hem de geçmiş tecrübelerimize dayanarak, hangi durumların churn etme nedeni olabileceğini tahmin etmeye çalışırdık. (Bir müşteri eğer son 2 ay alışveriş yapmamışsa artık alışveriş yapmayacaktır vb.) İşte bu bölümde, Einstein Analytics Studio , veriye bakarak , yuzdelerle bu değişkenleri bize söylüyor. Listede ilk sırada mobile_app_usage değerini %34 olarak görüyoruz. Mobil uygulama kullanma sıklığı %34 oranında churn edip etmeme kararında en etkili değişken. Bunun gibidaha aşağıda araç markasının %14 oranında etkili olduğunu görüyoruz. Bu sonuç veri seti random olduğu için tabiiki geçerli değil, ama modelin çıktılarını anlamlandırmak için bu değişkeni özellikle belirledim.</p><h3>Model evaluation — Overall performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*LL30mF37p1UKfvCpAy9Vsg.png" /><figcaption>Overall Performance</figcaption></figure><p>Model evaluation sekmesine geçtiğimizde, ilk ekran “overall performance” ekranı. Burada yukarıda açıkladığım AUC ile beraber , GINI ve MCC değerlerini görüyoruz. Yine teknik detaylarını ve hangi değerin modelin doğruluğu için kritik olduğu değerini her kavramın yanındaki ikona basarak görebiliyoruz.</p><p><strong>Accuracy Analiz</strong> bölümüne özellikle dikkat etmeliyiz; çünkü bu kısım, modelimizin gerçek değerlerle ne kadar örtüştüğünü ortaya koyar.<br> AUC değerini <strong>0.77</strong> olarak gördük. Bu değer 0.5’ten büyük olduğu için, modelin sınıflandırma başarısının anlamlı olduğunu ve güçlü tahminleme yaptığını söyleyebiliriz.</p><p>Bu bölümde <strong>dört temel metrik</strong> üzerinden değerlendirme yapılır:</p><ul><li><strong>True Positive (TP)</strong>: Modelin “churn edecek” dediği (pozitif) ve gerçekten churn eden kişilerin sayısıdır.</li><li><strong>True Negative (TN)</strong>: Modelin “churn etmeyecek” dediği (negatif) ve gerçekten churn etmeyen kişilerin sayısıdır.</li><li><strong>False Positive (FP)</strong>: Modelin “churn edecek” dediği ama gerçekte churn etmeyen kişilerin sayısıdır.</li><li><strong>False Negative (FN)</strong>: Modelin “churn etmeyecek” dediği ama gerçekte churn eden kişilerin sayısıdır.</li></ul><p>TP ve TN değerleri, modelin doğru tahminlerini; FP ve FN değerleri ise modelin yaptığı hataları gösterir.<br> Her bir metrik, modelin farklı yönlerden performansını değerlendirmemize olanak tanır (örneğin: hassasiyet, özgüllük, F1 skoru gibi).</p><p>Bu noktada Einstein Analytics Studio kullanırken, en temel veri bilimi kavramlarını örneğin “confusion matrix” tanımını bilmenin çok faydalı olacağını düşünüyorum.</p><p>Bir churn modelinde, TP,TN,FP,FN ‘nin önemi ne olabilir?</p><p>Modelimiz gerçekten churn etmeyen kişileri churn edecekmiş gibi gösteriyorsa, biz bu kişileri müşteri olarak tutabilmek için onlara kapmanya vb. yan faydalar, iletişim aktiviyeleri yaparak zaman ve bütçeyi doğru kullanmamış oluruz. Benzer şekilde modelimiz churn edecek kişileri churn etmeyecek gibi gösteriyorsa, biz de gerekli önlemleri almadığımız için müşterileri kaybedebiliriz.</p><h3>Gain ve Lift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*lQWvV8u4Qd9rU0KVJqHjKQ.png" /></figure><p>Modelin sonuçları ile ilgili bir diğer bilgi, “Gain” ekranı. Yine bu terimi duymamış bir kullanıcı için, Einstein Analytics Studio, gerekli açıklamayı yapıyor. Ekranda gözüken grafikte, ortada gözüken modelimize ait olan cizginin, en üste yakın, alttaki çizgiye uzak olmasına bakıyoruz. Bu durumda modelimiz güvenilir. Peki bu bilgi ne anlama geliyor? Yine acıklamada aslında bu grafiğin x ve y eksenlerinde modelin tüm churn edenleri yuzdelik olarak ne kadar doğru tahmin ettiği bilgisi var.</p><p>Bu kısmı Einstein Analytic Studio’dan bağımsız olarak, daha anlaşılır olması için açıklıyorum:</p><p>Veri setinde 1000 kişi olduğunu, 700 kişinin churn ettiğini 300 kişinin churn etmediğini tekrar belirterek devam ediyorum.</p><p>Öncelikle “perfect model” den başlayalım. Grafikte x ekseninde 0.7 degerine kadar artan , 0.7 değerinden sonra ise 1 olarak gözüken değerler var. Örneğin x değeri 0.1 olduğunda y değeri 0.14 oluyor. Bunların anlamı nedir?</p><p>Bu grafik önce veriyi churn edenlerden başlayarak sıralıyor. Biz x ekseninde 0.1 i aldığımızda, aslında bu sıralanmış olan verinin %10 unu almış oluruz. Bu %10 luk dilimde tamamen churn etmiş kişiler olacaktır. (ilk 700 satır tamamen churn edilmiş olanlar) y ekseninde ise bu %10 nun tüm churn edenlere oranını hesaplıyor. 100/700 = 0.14 . x ekseninde %20 yi alırsak, yine verinin tamamı (200 ) churn edenlerden oluşur, y ekseindeki değerde 200/700 =0.28 olur. Bu şekilde devam edersek , x ekseninde 0.7 değerini alırsak 700 adet churn eden kaydı almıs oluruz, y ekseinde de 700/700 = 1 değerini görürüz. x ekseninde daha buyuk değerleri aldığımızda 0.8, 0.9 vb. veri setimizde her zaman 700 churn eden bulunacağı için y ekseninde 1 değerini görüyoruz. Bu hesaplamayı modelimiz için yapıp, bulduğumuz değerin “perfect model”e ve “random model”e olan uzaklığına göre modelimizin doğruluğu hakkında karar verebiliyoruz. Bizim modelimiz 700 adet churn eden müşterinin hepsini doğru bilemedi, bu yüzden x eksenindeki farklı değerler içn biz perfect modelle aynı sonuçları görmüyoruz.</p><h3>Cross Validation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*t1E7nZg2lhTmAgB2jAEy5A.png" /><figcaption>Einstein Analytics Studio — Cross Validation</figcaption></figure><p>Modelin doğru sonuç verdiğini nasıl anlayabiliriz? Einstein Analytics Studio , model doğruluğunu “cross validation” yöntemi ile kontrol ediyor. Yukarıdaki ekranda, “cross validation” sonuçlarını görebiliyoruz. Veri seti,model eğitimi sırasında alt parçalara bölünüyor ve bu parçalar eğitim , test amacı ile ayrı ayrı kullanılıyor. 1000 satırlık verinin her defasında 4 parçaya bölündüğünü, (250 satırlık 4 parça) , 3 parçanın eğitim, 1 parçanında test için kullanıldığını düşünebiliriz. Bu işlemi de 4 kez tekrarlıyoruz. Ekran bu 4 işlemin istatistik sonuçlarını gösteriyor. Training set ve validation set değerlerini inceleyerek , yine yukarıda bahsettiğim kavramların aldığı sayısal değerlere göre modelin başarısı ve gücü hakkında fikir sahibi oluyoruz.</p><h3>Coefficients</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*inQCdU-E-XC5LubJiUtdmA.png" /><figcaption>Coefficients</figcaption></figure><p>Einstein Analytics Studio’nun model çalıştırırken, geleneksel makina öğrenmesine göre çok daha hızlı ilerlememizi sağladığı yerlerden bir tanesi de model değişkenlerini otomatik olarak hesaplaması. Yukarıdaki ekranda görmüş olduğumuz gibi, veri setimizde 8 temel değişken bulunurken, modele giren 1028 adet değişkeni Einsten Analytics Studio belirlemiş, ve önem sırasına göre de hesaplamış durumda. Üretilmiş olan bu farklı değişkenleri bir excel dosyası olarakte dışarıya çıkarmak mümkün. Bir veri bilimcinin uzun zaman haracayarak oluşturacağı değişkenleri, Einstein Anlaytcis Studio , çok hızlı bir şekilde oluşturup modeli eğitiyor.</p><h3>Predictions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*kLCpAzZzzkksSZCsQNWjZQ.png" /><figcaption>Predictions</figcaption></figure><p>Einstein Analytics Studio, tahminleri kayıt seviyesinde görebilmemizi sağlıyor. Yukarıda gözüktüğü gibi, her bir kayıt için, o kayda ait veri alanları, tahmin edilen değer ve gerçekleşen değer bilgilerini görerek, kayıt seviyesinde detaylı inceleme yapabiliyoruz.</p><h3>Threshold Evaluation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*Uvqubqaatcfe1Hhl-bOSFA.png" /><figcaption>Threshold Evaluation</figcaption></figure><p>Churn etme kararının bir olasılık ile belirlendiğini, bunu arttırıp azaltmanın da modele etkisi olacağını belirtmiştim. Threshold evaluation ekranında , threshold değerinin değişmesinin modele olan etkisinin simulasyonu yapılıyor. Girilen değerlerden sonra Apply buttonua basılırsa, sağ alt köşeden gözüken “confusion matris” değerleri de uygun şekilde güncelleniyor.Böylece threshold değerinin etkisini de izleyebiliyoruz.</p><h3>Model Tournament</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nnYww89KulyPB8xlLkiTQ.png" /><figcaption>Model seçimi</figcaption></figure><p>Bir diğer önemli özellikte, Einstein Analytics Studio’nun XGBoost,Random Forest vb. algoritmaları seçmemize imkan tanıması , ek olarak istersek “model tournament” seçerek, tüm modellerin denenip en iyi sonucu verenin otomaik olarak seçilmesini sağlayabiliyoruz.</p><h3>Model Karşılaştırma</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*awHwiLNLWoBjpFHg0_VNMA.png" /><figcaption>Model Karşılaştırma</figcaption></figure><p>Modellerin farklı zamanlarda elde ettiği sonuçları ayrı ayrı görebildiğimiz gibi , 2 modeli karşılaştırabiliyoruz. Yukarıda farklı zamanlarda çalıştırdığım iki model için bir karşılaştırma çalıştırıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*75rmCjsHR08GGMZ7reQMLg.png" /><figcaption>Karşılaştırma Raporu</figcaption></figure><p>Raporun verdiği ilk bilgi her 2 modelde hangi algoritmanın kullanıldığı bilgisi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*RXcv1_MqMVSxxcc7bwWLHg.png" /><figcaption>Karşılaştırma Raporu</figcaption></figure><p>Raporun devamında, 2 raporun detaylı istatsitik karşılaştırmasını görüyoruz.</p><h3>Model Deploy</h3><p>Modeli çalışır hale getirmek istediğimizde, istersek Salesforce içerisinde bir data nesnesine bağlayarak veya bir rest api ile çağırarak çalıştırabiliyoruz.</p><h3>Sonuç</h3><p>Einstein Analytics Studio çok güçlü bir autoML aracı. Burada açıkladığım özelliklerinin yanında, veri seti içerisinde yer alan alanlar bazında detaylı analizler, bias analizleri vb. bir çok zengin özellik içeriyor. Veriden değer yaratma yolculuğunda, veri biliminin demokratikleşmesi için önemli bir araç .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a78594c0f6a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AutoML with Salesforce Einstein Analytics Studio]]></title>
            <link>https://medium.com/@utolgaevren/automl-with-salesforce-einstein-analytics-studio-aef43d0e8568?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef43d0e8568</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 20:54:58 GMT</pubDate>
            <atom:updated>2025-08-24T20:54:58.969Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Data science</strong> is a field that brings together various disciplines such as mathematics, statistics, and engineering. It can be complex both in terms of reaching results and interpreting them.</p><p>With the increasing adoption of <strong>generative AI (GenAI)</strong>, I believe we are experiencing a similar process in data science to what we previously saw in the democratization of data.</p><p>Today, many professionals from various domains — especially <strong>business intelligence experts working in business units</strong> — can carry out data science tasks much faster.</p><p>In this article, I will perform a <strong>churn analysis</strong> using a sample dataset and <strong>Salesforce Einstein Analytics Studio</strong>, a tool that allows fast data modeling and analytical model development <strong>without requiring any coding</strong>.</p><p><strong>First</strong>, I created a <strong>synthetic and randomly generated dataset</strong> using ChatGPT. The dataset includes the following columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*CsZPcPHXjk8shBkYL4kAXA.png" /><figcaption>Sample Data Set</figcaption></figure><p>The sample dataset contains entirely <strong>randomly generated data</strong> about end-users who make purchases at <strong>fuel stations</strong>.<br> While selecting the features, I included both <strong>behavioral variables</strong> such as <em>monthly average station visits</em> and <em>loyalty program membership</em>, as well as <strong>demographic variables</strong> like <em>car brand</em>.<br> Since the data is completely synthetic, I do not expect the <strong>analysis results</strong> to be highly meaningful.<br> However, being able to <strong>quickly and effortlessly perform multiple model-related checks</strong> using <strong>Einstein Analytics Studio</strong> makes the process remarkably efficient.<br> Let’s now proceed step by step.<br> First, let’s take a look at the <strong>general interface</strong> of Einstein Analytics Studio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MwFS2POsUXAzRR6uHcGuQ.png" /></figure><h3>Data Loading</h3><p>When we enter <strong>Einstein Analytics Studio</strong>, we use the <strong>“Create” button</strong> located at the top right corner to create elements such as <strong>datasets</strong> and <strong>models</strong>. From this menu, we select <strong>“Dataset”</strong> to upload our data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*D0-0P8O9nx-WNJVPyfgIKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*0z4WPKCrA9dCLQ8oC-O9gA.png" /></figure><p>Right after uploading the data, we can analyze the contents of the dataset either by manually selecting the relevant columns or by describing what we want to do in natural language:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*SDerZM0BRiibqx5RvXzd-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*tW5xeDSHVkwMrouTscKmxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*dWOi417hcYEFfNglsNTRNA.png" /></figure><p>I created a sample dataset with 1,000 rows, consisting of 700 churned and 300 non-churned customers. Within the data analysis menu of Einstein Analytics Studio, it is possible to visualize the data in various ways. Additionally, being able to view all the actions performed in a historical log is a very useful feature.</p><p>Using these capabilities, basic data analysis can be performed directly — without the need for technical expertise in reporting.</p><p>We’ve uploaded the data and performed basic analyses. Now, let’s move on to the modeling phase</p><h3>Model Creation</h3><p>In Einstein Analytics Studio, we create an analytical model either by using the <strong>“Create”</strong> button (which we also used while uploading the data), or by clicking the <strong>“Create Model”</strong> button within the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*0Hk-xmSITF8xU6vB4Gvz4g.png" /></figure><p>The model creation process is designed to be fully outcome-oriented. First, we select what we want to predict from the columns of our dataset. In our example, we want to predict churned users, and our dataset includes a column named <strong>churned</strong> (1: churned, 0: not churned). We select the <strong>churned</strong> field.</p><p>After making this selection, we define our objective for the prediction in the <strong>“So I can”</strong> section — choosing either <strong>minimize</strong> or <strong>maximize</strong>, and then indicating which value we’re targeting.<br> For example, if we select <strong>maximize churned:0</strong>, it means we want the model to maximize the number of users predicted as not churned.</p><p>Then, we click <strong>Next</strong> to proceed to the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*AM7R4REexhXNr2QSsKk2aQ.png" /></figure><p>In the next menu, we can either let <strong>Einstein Analytics Studio</strong> automatically determine the model variables (leaving the decision to the system), or manually select the variables we want to include.<br> We proceed by choosing the automatic option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*GN3nS13VL9atRgrcLXSkNg.png" /></figure><p>From this point on, <strong>Einstein Analytics Studio</strong> runs the model. Running the model consists of various data science development processes such as <strong>training</strong>, <strong>testing</strong>, and <strong>validating</strong> the model.</p><p>Once the model processing is complete, Einstein Analytics Studio provides the user with both <strong>technical evaluation reports</strong> of the model and <strong>detailed business insights</strong>.</p><p>Now, let’s take a closer look at what <strong>Einstein Analytics Studio offers as an AutoML tool</strong>.</p><h3>Reviewing the model results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*o4R3okJRM3WbymnKOO5Kvg.png" /></figure><p>After the model has finished running, the results page shown above opens. On the left side of this page, there are options for model performance (the screen currently visible in the image above), model settings, predictions, and data insights. Let’s start with performance</p><h3>Performans -&gt; Overview</h3><p>After summarizing the purpose of the model, Einstein Analytics Studio defines the model’s success criteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*YeQdA-ycGy5LH4pvZw7_7Q.png" /></figure><h3>AUC</h3><p><strong>The first value is AUC.</strong> The model trained on our sample data has an AUC score of <strong>0.77</strong>. The concept of AUC is typically well-known to data scientists, but how can a non-data scientist user — someone who wants to create value from data through modeling — interpret this value?</p><p><strong>Einstein Analytics Studio provides clear explanations</strong> for all such technical concepts. For example, in the screenshot above, when you click the icon next to the label “AUC”, it shows what the AUC value means and what range of values are considered acceptable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*qzfo-qYSE0_w9ABjJo7vdA.png" /></figure><p>From the explanation, we understand that this metric indicates how well our model classifies correctly. If the value is below 0.5, our model is performing like a random guesser. The closer it is to 1, the better the predictive power. However, if the value is <strong>exactly 1</strong>, it may indicate a problem with the data (such as overfitting or data leakage).</p><p><strong>In my opinion</strong>, for users who are not data scientists but want to quickly run models using methods typically used by data scientists, <strong>Einstein Analytics Studio provides clear and understandable outputs</strong>.</p><p>The AUC value of this analytical model I created using synthetic data is <strong>0.77</strong>. As mentioned in the explanation, it is greater than 0.5 but not 1. So, I can assume the model performed well.</p><p><strong>Let’s continue — what other metrics should I check?</strong></p><h3>Threshold</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*D6_Pd3eqG3mI3tkikb09cQ.png" /><figcaption>Threshold</figcaption></figure><p>The second result value presented by <strong>Einstein Analytics Studio</strong> is the <strong>“threshold.”</strong> In the figure, the red and green areas and the number <strong>0.6996</strong> between them indicate the probability level at which the model decides whether a customer has churned.</p><p>If the model calculates a churn probability <strong>equal to or above 0.6996</strong>, it classifies the customer as <strong>churned</strong>. If the probability is <strong>below 0.6996</strong>, the customer is considered <strong>not churned</strong>.</p><p><em>This threshold value </em><strong><em>can be adjusted</em></strong><em> in the model details.</em></p><p>Changing this value allows us to make the model either <strong>more flexible</strong> or <strong>more strict</strong> in its decision-making:</p><ul><li>If we <strong>increase</strong> the threshold, the model will be <strong>stricter</strong>, only flagging customers who are very likely to churn.</li><li>If we <strong>decrease</strong> the threshold, the model will be <strong>more lenient</strong>, possibly labeling even some loyal customers as churned.</li></ul><p>It’s important to remember that this is a <strong>modeling exercise</strong>, and the goal is not to find absolute truth, but rather to produce results that are <strong>as close to reality as possible</strong>.</p><p><strong>“All models are wrong, but some are useful.”</strong><br> — <strong>George E. P. Box</strong></p><h3>Data Control</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*UoYWO7xeA-hb5grWy0JaIQ.png" /></figure><p>In the <strong>“Assess Deployment Readiness”</strong> section, <strong>Einstein Analytics Studio</strong> provides insight into whether there are any issues or important conditions to be aware of in the dataset. If a problem is detected, it also <strong>guides the user on what actions to take</strong>.</p><p>In my case, the system identified two issues in the dataset. One of the findings stated that <strong>“cross-validation failed.”</strong><em>For users who have never heard of this term before, the platform offers a </em><strong><em>clear and sufficient explanation</em></strong><em>.</em></p><p>I will return to this detail later, but I want to emphasize the phrase “sufficient and necessary explanation.” It is <strong>necessary</strong> to explain what the term means, but <strong>it is not required</strong> to go into full technical depth. Einstein Analytics Studio facilitates progress by providing just enough technical explanation to <strong>help users focus on business outcomes</strong> rather than technical complexities.</p><h3>Training data and model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*MJE1KQFuTduireS5dImrQA.png" /></figure><p>At the bottom left of the same screen, in the <strong>“Distribution of Outcome Variable”</strong> section, the distribution of churned and non-churned customers in the dataset is displayed. In our dataset, we had created <strong>700 churned</strong> and <strong>300 non-churned</strong> customers.</p><p>On the right side, under the <strong>“Top Predictors”</strong> section, we can see the variables that had the <strong>greatest impact on the model’s decision</strong> to predict churn or not.</p><p>If we were to analyze this dataset manually, we would try to <strong>guess which factors might lead to churn</strong>, based both on what we observe in the data and on past experience. (For example, we might assume that if a customer hasn’t shopped in the last two months, they are unlikely to shop again.)</p><p>This is exactly what Einstein Analytics Studio does in this section — it examines the data and shows us these influential variables <strong>with percentages</strong>.</p><p>At the top of the list, we see that <strong>mobile_app_usage</strong> contributes <strong>34%</strong>, making it the most important predictor of churn behavior. Similarly, we see that <strong>vehicle_brand</strong> contributes <strong>14%</strong>, which I deliberately included to illustrate how the model ranks variable importance. (Of course, since this dataset is randomly generated, this specific result isn’t meaningful.)</p><h3>Model evaluation — Overall performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*LL30mF37p1UKfvCpAy9Vsg.png" /><figcaption>Overall Performance</figcaption></figure><p>When we switch to the <strong>Model Evaluation</strong> tab, the first screen we see is the <strong>“Overall Performance”</strong> screen. Here, along with the previously explained <strong>AUC</strong>, we also see the <strong>GINI</strong> and <strong>MCC</strong> values.</p><p>Once again, by clicking the icons next to each of these terms, we can view their <strong>technical explanations</strong> and <strong>which value ranges are critical for assessing the model’s accuracy</strong>.</p><p>We should <strong>pay special attention to the Accuracy Analysis section</strong>, because this part reveals <strong>how well our model aligns with actual values</strong>.</p><p>We previously saw that the <strong>AUC value is 0.77</strong>. Since this value is greater than 0.5, we can say that the <strong>model’s classification performance is meaningful</strong> and that it provides <strong>strong predictive capability</strong>.</p><p>In this section, the evaluation is made based on <strong>four key metrics</strong>:</p><ul><li><strong>True Positive (TP):</strong> The number of people the model predicted as “will churn” (positive), and who actually did churn.</li><li><strong>True Negative (TN):</strong> The number of people the model predicted as “will not churn” (negative), and who indeed did not churn.</li><li><strong>False Positive (FP):</strong> The number of people the model predicted as “will churn”, but who in reality did <strong>not</strong> churn.</li><li><strong>False Negative (FN):</strong> The number of people the model predicted as “will not churn”, but who in fact <strong>did</strong> churn.</li></ul><p><strong>The TP and TN values</strong> represent the model’s correct predictions, while <strong>FP and FN values</strong> show the model’s mistakes.</p><p>Each of these metrics allows us to assess the model’s performance from different perspectives (such as sensitivity, specificity, F1 score, etc.).</p><p>At this point, I believe that knowing the basic data science concepts — such as the definition of a <strong>confusion matrix</strong> — can be very helpful when using Einstein Analytics Studio.</p><p>Now, what is the significance of TP, TN, FP, and FN in a churn model?</p><ul><li>If our model incorrectly classifies people who are <strong>not actually churning</strong> as if they <strong>will churn</strong> (False Positives), we might waste time and budget by offering them unnecessary <strong>campaigns, benefits, or communication activities</strong> to try to retain them.</li><li>Similarly, if the model wrongly predicts that people <strong>won’t churn</strong>, when in fact they <strong>will</strong> (False Negatives), we may <strong>lose those customers</strong> due to not taking the necessary preventive measures.</li></ul><h3>Gain and Lift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*lQWvV8u4Qd9rU0KVJqHjKQ.png" /></figure><p>Another piece of information regarding the model results is the <strong>“Gain” chart</strong>. Again, for a user who has not heard of this term before, Einstein Analytics Studio provides a clear explanation.</p><p>In the graph shown on the screen, we look at how <strong>close the line representing our model</strong> (the one in the middle) is to the top of the chart and how <strong>far it is from the bottom line</strong>. The closer it is to the top and farther from the bottom, the <strong>more reliable the model</strong> is.</p><p>But what does this information actually mean?</p><p>According to the explanation, the <strong>x and y axes</strong> of this chart represent how well the model predicts <strong>all churners as a percentage</strong>.</p><p>Let me now explain this part <strong>independently of Einstein Analytics Studio</strong> to make it even more understandable:</p><p>Let’s assume there are <strong>1,000 people</strong> in the dataset.<br> Out of these, <strong>700 are churners</strong>, and <strong>300 are non-churners</strong>.</p><p>Let’s start with the <strong>“perfect model”</strong>. On the graph, we see values on the <strong>x-axis increasing up to 0.7</strong>, and then becoming 1 after 0.7. For example, when the <strong>x-value is 0.1</strong>, the <strong>y-value is 0.14</strong>. What do these mean?</p><p>This chart sorts the data <strong>starting from churners</strong>. When we take <strong>0.1 on the x-axis</strong>, it means we’re selecting the <strong>top 10% of the sorted dataset</strong>. This top 10% consists <strong>entirely of churners</strong> (i.e., the first 700 rows are all churned customers). On the y-axis, it shows the proportion of these to the <strong>total number of churners</strong>.<br> So:<br> <strong>100/700 = 0.14</strong>.</p><p>If we take <strong>20% on the x-axis</strong>, we still get only churners (first 200), and the y-value becomes:<br> <strong>200/700 = 0.28</strong>.</p><p>If we continue like this, when we reach <strong>0.7 on the x-axis</strong>, we’ve collected <strong>700 churners</strong>, and on the y-axis, we see:<br> <strong>700/700 = 1</strong>.</p><p>For values <strong>greater than 0.7</strong> on the x-axis (e.g., 0.8, 0.9…), since our dataset has <strong>only 700 churners</strong>, we continue to see <strong>1 on the y-axis</strong>.</p><p>By performing this calculation for our own model and comparing the result to the <strong>“perfect model”</strong> and <strong>“random model”</strong>, we can evaluate the <strong>accuracy of our model</strong>.</p><p>Since our model cannot perfectly identify all 700 churners, we <strong>do not see the same results</strong> as the perfect model for various x-values.</p><h3>Cross Validation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*t1E7nZg2lhTmAgB2jAEy5A.png" /><figcaption>Einstein Analytics Studio — Cross Validation</figcaption></figure><p><strong>How can we understand whether the model gives accurate results?</strong><br> Einstein Analytics Studio verifies model accuracy using the <strong>cross-validation</strong> method.</p><p>In the screen shown above, we can see the <strong>cross-validation results</strong>. During model training, the dataset is divided into smaller parts, and these parts are used separately for training and testing purposes.</p><p>For example, you can think of a 1000-row dataset being split into <strong>4 parts (each with 250 rows)</strong>. In each round, <strong>3 parts are used for training</strong> and <strong>1 part is used for testing</strong>. This process is repeated <strong>4 times</strong>, and the screen displays the statistical results of these 4 iterations.</p><p>By examining the <strong>training set</strong> and <strong>validation set</strong> values, and reviewing the numerical values of the performance metrics mentioned earlier (e.g., AUC, GINI, MCC), we can gain insight into the <strong>success and strength of the model</strong>.</p><h3>Coefficients</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*inQCdU-E-XC5LubJiUtdmA.png" /><figcaption>Coefficients</figcaption></figure><p>One of the features that allows <strong>Einstein Analytics Studio</strong> to advance much faster than traditional machine learning approaches during model building is its ability to <strong>automatically compute model variables</strong>.</p><p>As seen in the screen above, although our dataset contains only <strong>8 core variables</strong>, <strong>Einstein Analytics Studio has generated 1,028 input variables</strong> for the model and has also <strong>ranked them by importance</strong>. It is possible to <strong>export these generated features</strong> as an Excel file.</p><p>In traditional workflows, a data scientist would need to spend <strong>a significant amount of time</strong> to create these features manually. However, <strong>Einstein Analytics Studio generates them quickly and uses them to train the model efficiently.</strong></p><h3>Predictions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*kLCpAzZzzkksSZCsQNWjZQ.png" /><figcaption>Predictions</figcaption></figure><p><strong>Einstein Analytics Studio allows us to view predictions at the record level.</strong><br> As shown above, we can examine each record in detail by seeing the <strong>data fields for that record</strong>, the <strong>predicted value</strong>, and the <strong>actual outcome</strong>. This enables <strong>granular-level analysis</strong> of model performance.</p><h3>Threshold Evaluation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*Uvqubqaatcfe1Hhl-bOSFA.png" /><figcaption>Threshold Evaluation</figcaption></figure><p><strong>I had previously mentioned that the churn decision is determined by a probability, and that increasing or decreasing this probability (threshold) affects the model.</strong><br> On the <strong>Threshold Evaluation</strong> screen, the system simulates how changing the threshold value affects the model.<br> When you enter new threshold values and click the <strong>Apply</strong> button, the <strong>confusion matrix</strong> displayed in the bottom-right corner is updated accordingly.<br> This allows us to <strong>observe the impact of the threshold value</strong> on model performance in real time.</p><h3>Model Tournament</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nnYww89KulyPB8xlLkiTQ.png" /></figure><p><strong>Another important feature</strong> is that <strong>Einstein Analytics Studio allows us to choose algorithms</strong> such as <strong>XGBoost, Random Forest</strong>, etc.<br> Additionally, if we wish, we can select the <strong>“Model Tournament”</strong> option, which automatically <strong>tests all available models</strong> and <strong>selects the one that provides the best results</strong>.</p><h3>Model Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*awHwiLNLWoBjpFHg0_VNMA.png" /></figure><p><strong>We can view the results obtained by models at different times separately</strong>, and we can also <strong>compare two models</strong>.<br> In the example above, I am <strong>running a comparison between two models</strong> that I executed at different times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*75rmCjsHR08GGMZ7reQMLg.png" /></figure><p>The first piece of information provided by the report is which algorithm was used in both models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*RXcv1_MqMVSxxcc7bwWLHg.png" /></figure><p>In the following section of the report, we see a detailed statistical comparison of the two models.</p><h3>Model Deploy</h3><p>When we want to make the model operational, we can either connect it to a data object within Salesforce or run it via a REST API call.</p><h3>Final Word</h3><p>Einstein Analytics Studio is a powerful AutoML tool. In addition to the features I’ve explained here, it includes many advanced capabilities such as detailed field-level analyses and bias analyses within the dataset. It is an important tool in the journey of creating value from data, supporting the democratization of data science.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef43d0e8568" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are We Getting the Most Out of GPUs? — III]]></title>
            <link>https://medium.com/@utolgaevren/are-we-getting-the-most-out-of-gpus-iii-b0a7be930380?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0a7be930380</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 09:56:55 GMT</pubDate>
            <atom:updated>2025-06-23T09:56:55.639Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@utolgaevren/are-we-getting-the-most-out-of-gpus-ii-4931fc7e6018?source=your_stories_page--------------------------------------------">Are We Getting the Most Out of GPUs? — II</a>I</h3><p>GPUs are high-cost and limited resources. Are we truly utilizing them efficiently and effectively? In this article, I discuss monitoring and optimization methods for GPU usage.</p><p><a href="https://medium.com/@utolgaevren/are-we-using-our-gpus-efficiently-an-introduction-to-gpu-monitoring-and-optimization-449cd1596d22">You can read the first part of the series here.</a></p><p><a href="https://medium.com/@utolgaevren/are-we-getting-the-most-out-of-gpus-ii-4931fc7e6018">You can read the second part of the series here.</a></p><p>When I began exploring this topic, I asked myself the following questions:</p><ol><li>How optimized are the operations running on GPUs, and how can I measure it?</li><li>What does optimization on a GPU even mean?</li><li>What kinds of operations can we use on GPUs? Deep learning, machine learning, data transformation — what’s most suitable?</li><li>Should I use CUDA C, or should I go with Python libraries like PyCUDA or CuPy?</li><li>How can I monitor the performance of the code I’ve written using Python on a GPU?</li><li>Which is better for data processing on GPUs: pandas, Spark, or cuDF?</li></ol><p>In the first and second parts of this series, we discussed methods for measuring GPU performance (such as <em>ncu</em>, NVIDIA Nsight Compute, etc.). We explored how to run code on the GPU using CUDA with C and Python, how much of the GPU’s capacity is utilized by the code, and how to identify performance bottlenecks.</p><p>Next, we compared pandas and cuDF in Python for data engineering tasks, demonstrating with examples how data transformations can be performed on the GPU. We also analyzed the cuDF-based Python code using ncu, observing how effectively the code utilizes GPU resources, and we even examined the cuDF source code to understand the implementation in more detail.</p><p>In this third part, we will investigate how much performance gain traditional machine learning workloads can achieve on the GPU. For this, we will use cuML, a library designed for machine learning on GPUs, similar to how cuDF is used for GPU-accelerated DataFrame operations.</p><p>Let’s start with a simple Linear Regression test. We run linear regression with sklearn on 100,000 data points — this is on the CPU, not the GPU yet.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import time<br>import sklearn<br>from sklearn.linear_model import LinearRegression<br>num=100000<br>w = 20<br>x = np.random.normal(size=(num))<br>b=1<br>y = w*x+b<br>randomdata = np.random.normal(scale=20.0,size=(num))<br>y_randomdata = y+randomdata<br><br><br>print(sklearn.__version__)<br>lr = LinearRegression()<br>print(lr)<br>start_fit = time.perf_counter()<br><br>model=lr.fit(np.expand_dims(x,1),y_randomdata)<br><br>end_fit = time.perf_counter()<br><br>fit_time = end_fit - start_fit<br>print(f&quot;Fitting time: {fit_time:.6f} seconds&quot;)<br><br>predictinputs = np.linspace(-5,5,num=num)<br>print(predictinputs)<br><br>start_pred = time.perf_counter()<br>predictoutputs=lr.predict(np.expand_dims(predictinputs,1))<br>end_pred = time.perf_counter()<br><br><br>pred_time = end_pred - start_pred<br>print(f&quot;Prediction time: {pred_time:.6f} seconds&quot;)<br>print(predictoutputs)<br><br>r2 = lr.score(np.expand_dims(x,1), y_randomdata)<br>print(f&quot;R² score: {r2}&quot;) <br><br>plt.scatter(x,y_randomdata,label=&quot;data&quot;)<br>plt.plot(x,y,color=&quot;red&quot;,label=&quot;math.truth&quot;)<br>plt.plot(predictinputs,predictoutputs,color=&quot;green&quot;,label=&quot;prediction&quot;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*MVfBuSi7pRQJZ3rkhuxncQ.png" /></figure><p>Training the model on 100,000 rows takes 0.007 seconds, and making predictions on 100,000 values takes 0.0009 seconds. The model performs poorly with an R² score of 0.5, but our goal here is not the model’s accuracy — it’s to measure performance.<br> Let’s experiment by increasing the amount of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*mC3WwuPo6NUwpxMdR9KZ8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*hI3wevwUQvWkuKsFu0vx5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2RVaYAfxDT3dC0cQxXnziw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZjB88thW8b4ClxRi8khR_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dJERYIQKa4ZyXQGpIN3bSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*r4kfUU91XIAkIqZYks5KrA.png" /></figure><p>As the data grows, the time required to train the model increases significantly, while the increase in prediction time is much smaller compared to training.<br> Now, we will perform these experiments on the GPU using cuML.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import time<br>import cudf<br>from cuml.linear_model import LinearRegression as LRGPU<br>import cupy as cp<br>num=100000<br>w = 20<br>x = np.random.normal(size=(num))<br>b=1<br>y = w*x+b<br>randomdata = np.random.normal(scale=20.0,size=(num))<br>y_randomdata = y+randomdata<br>print(&quot;number  of elements&quot;,num)<br>start_dfcreation = time.perf_counter()<br>df_gpu = cudf.DataFrame({&#39;x&#39;: x, &#39;y&#39;: y_randomdata})<br>end_dfcreation = time.perf_counter()<br>print(f&quot;DataFrame(fit) creation time: {end_dfcreation - start_dfcreation:.6f} seconds&quot;)<br>lrgpu = LRGPU(solver=&#39;svd&#39;)<br><br>start_fit = time.perf_counter()<br>lrgpu.fit(df_gpu[[&#39;x&#39;]],df_gpu[&#39;y&#39;])<br>end_fit = time.perf_counter()<br>fit_time = end_fit - start_fit<br>print(f&quot;Fitting time: {fit_time:.6f} seconds&quot;)<br>r2 = lrgpu.score(df_gpu[[&#39;x&#39;]],df_gpu[&#39;y&#39;])<br>print(f&quot;R² score: {r2}&quot;)<br><br>predictinputs = np.linspace(-5,5,num=num)<br>start_dfcreation = time.perf_counter()<br>df_cudf = cudf.DataFrame({&#39;inputs&#39;: predictinputs})<br>end_dfcreation = time.perf_counter()<br>print(f&quot;CUDF (Prediction) DataFrame creation time: {end_dfcreation - start_dfcreation:.6f} seconds&quot;)<br><br>start_pred = time.perf_counter()<br>predictoutputs = lrgpu.predict(df_cudf[[&quot;inputs&quot;]])<br>end_pred = time.perf_counter()<br>pred_time = end_pred - start_pred<br>print(f&quot;Prediction time: {pred_time:.6f} seconds&quot;)<br><br>plt.scatter(x,y_randomdata,label=&quot;data&quot;)<br>plt.plot(x,y,color=&quot;red&quot;,label=&quot;math.truth&quot;)<br>plt.plot(predictinputs,predictoutputs.to_numpy(),color=&quot;green&quot;,label=&quot;prediction&quot;)<br>plt.legend()</pre><p>Almost the same code, but instead of sklearn, we use cuML. With cuML, we run ML algorithms on the GPU, and with cuDF, we perform dataframe operations on the GPU as well. I run this code again by increasing the number of data points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*fkgiZVaNM1Y95P0UzM9McA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*g4EWTzo1UlcvBeb0R9JVRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*9gha6xMJkdxHFxRC2UzlCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*0knz8TVzdqRVPuvPkBwCSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*7GKM4MW1YNTwyYlp2sI8Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*BcpEv1Qo0njq_RSw3_tcDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*R4ZNDWJEOdkHZV9RvHV_aQ.png" /></figure><p>Let’s summarize these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*T62UfJlrePW3kVgrLZUv-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ISinwXRPUz3rF4AHWwBf_A.png" /></figure><p>As the data grows, the time to copy the data into GPU memory increases linearly, but the increase in model execution time is much smaller.<br> Let’s now compare our previous runs on the CPU with those on the GPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yzHTjP3wxJZQSA7tzNapFQ.png" /></figure><p>As the data grows, model execution time on the CPU increases linearly. However, on the GPU, the execution is significantly faster, and the increase in data size does not cause the same level of delay as it does on the CPU.<br> As before, I also conducted an analysis for 100 million rows using NVIDIA Nsight Compute (ncu):</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*JCIBSwbmeYHG0uRcg-nTFg.png" /></figure><p>In the previous section, I examined the source code of cuDF and tried to understand the purpose of each kernel function listed in the output above. Additionally, by placing print statements at each stage of the Python program where we collected the ncu output, I was able to identify which kernel functions correspond to which parts of the code. I’m following the same approach for cuML as well. For the 100 million row case, the longest duration—594 ms—was observed in the geqr2_gmem_domino kernel. Let’s take a look at the detailed page for this kernel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*VkjrTRT88mWpwOnq2eCqPA.png" /></figure><p>This point made me think: wouldn’t this operation complete faster if it ran with greater parallelism? The Roofline analysis (the output a bit lower on the detail page — I’ve included a visual below) suggests exactly that. We can determine that we are operating below the GPU’s computational capacity by looking at the position of the orange dot in the graph. It’s located lower and far from the curve. So, what can we do with this result? This kernel runs with a block size of 512 (we can see this on the far right of the summary page). When we were working with CUDA C before, we could manually adjust the parallelism parameters, but in this case, we’re using cuML — we don’t want to modify the library code ourselves. So I’ll stop here. (Still, I’ve raised this as a question on the RAPIDS GitHub page.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZiqM8Qi5hROxeuhCAfmv1g.png" /></figure><p>I believe this concludes a sufficiently detailed ncu analysis. In a similar way, I’ve seen that it’s also possible to analyze how high-level languages utilize the GPU.<br>In the next part, I will continue with Dask.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0a7be930380" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPU’ların Hakkını Veriyor muyuz? — III]]></title>
            <link>https://medium.com/@utolgaevren/gpular%C4%B1n-hakk%C4%B1n%C4%B1-veriyor-muyuz-iii-28cb2e0161da?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/28cb2e0161da</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 09:56:35 GMT</pubDate>
            <atom:updated>2025-06-23T09:56:35.630Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@utolgaevren/gpular%C4%B1n-hakk%C4%B1n%C4%B1-veriyor-muyuz-ii-c21dd78dcf43?source=your_stories_page--------------------------------------------">GPU’ların Hakkını Veriyor muyuz? — II</a>I</h3><h4>GPU’lar yüksek maliyetli ve sınırlı kaynaklar. Acaba GPU’ları verimli ve etkin bir şekilde kullanıyor muyuz? Bu yazıda GPU kullanımının izlenme ve optimizasyon yöntemlerinden bahsediyorum.</h4><p><a href="https://medium.com/@utolgaevren/gpular%C4%B1n-hakk%C4%B1n%C4%B1-veriyor-muyuz-f34d216793e3">Serinin birinci bölümünü buradan okuyabilirsiniz</a></p><p><a href="https://medium.com/@utolgaevren/gpular%C4%B1n-hakk%C4%B1n%C4%B1-veriyor-muyuz-ii-c21dd78dcf43">Serinin ikinci bölümünü buradan okuyabilirsiniz</a></p><p>Bu konuyu incelemeye başladığımda şu soruları sordum:</p><p>1. GPU’larda çalıştırılan işlemler ne kadar optimize çalışıyor nasıl anlayabilirim?</p><p>2. GPU’da optimizasyon yapmak ne demek?</p><p>3. GPU’da ne tür işlemleri kullanabiliyoruz? Deep learning , Ml , data transformation vb. hangisi uygun?</p><p>4. C Cuda mı kullanmalıyım , yoksa Pythonda PyCUDA veya CuPy mı?</p><p>5. Python’da GPU kullanarak yazdığım kodun GPU performansını nasıl görebilirim?</p><p>6. GPU , pandas,spark hangisi daha iyi?</p><p>Bu yazının 1. ve 2. bölümünde GPU performansını ölçme yöntemlerinden ( ncu , nvidia nsight compute vb) bahsetmiş, c ve python üzerinde cuda ile GPU üzerinde nasıl kod çalıştırdığımızı ve kodların GPU’yu ne kadar kullandığını, darboğazların nerede olduğunu nasıl anlayacağımızı incelemiş, sonrasında ise data engineering için python ile pandas ve cuDF karşılaştırması yaparak GPU üzerinde data transformasyonunun nasıl yapıldığını örneklerle açıklamıştık. Yine pythonda cuDF ile yazdığımız kodları ncu ile analiz ederek , bu kodların GPU’yu nasıl kullandığınıda analiz etmiş , cuDF kaynak koduna kadar da konuyu detaylandırmıştık. 3.bölümde geleneksel makina öğrenmesi işlerinin GPU’da ne kadar performans artışı sağladığını inceleyeceğiz. Bunun için dataframeler için kullandığımız cuDF benzeri cuML kullanacağız.</p><p>Öncelikle basit bir Lineer Regresyon testi ile başlayalım. sklearn ile 100bin data için lineer regresyon çalıştırıyoruz , CPU üzerinde, henüz GPU’da değiliz:</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import time<br>import sklearn<br>from sklearn.linear_model import LinearRegression<br>num=100000<br>w = 20<br>x = np.random.normal(size=(num))<br>b=1<br>y = w*x+b<br>randomdata = np.random.normal(scale=20.0,size=(num))<br>y_randomdata = y+randomdata<br>#plt.scatter(x,y)<br><br><br>print(sklearn.__version__)<br>lr = LinearRegression()<br>print(lr)<br>start_fit = time.perf_counter()<br><br>model=lr.fit(np.expand_dims(x,1),y_randomdata)<br><br>end_fit = time.perf_counter()<br><br><br>fit_time = end_fit - start_fit<br>print(f&quot;Fitting time: {fit_time:.6f} seconds&quot;)<br><br>predictinputs = np.linspace(-5,5,num=num)<br>print(predictinputs)<br><br>start_pred = time.perf_counter()<br>predictoutputs=lr.predict(np.expand_dims(predictinputs,1))<br>end_pred = time.perf_counter()<br># -----&gt; Zaman ölçüm bitiş<br><br>pred_time = end_pred - start_pred<br>print(f&quot;Prediction time: {pred_time:.6f} seconds&quot;)<br>print(predictoutputs)<br><br>r2 = lr.score(np.expand_dims(x,1), y_randomdata)<br>print(f&quot;R² score: {r2}&quot;) #1 e  yakınsa  iyi<br><br><br>plt.scatter(x,y_randomdata,label=&quot;data&quot;)<br>plt.plot(x,y,color=&quot;red&quot;,label=&quot;math.truth&quot;)<br>plt.plot(predictinputs,predictoutputs,color=&quot;green&quot;,label=&quot;prediction&quot;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*MVfBuSi7pRQJZ3rkhuxncQ.png" /></figure><p>100bin satır için modeli eğitmek 0.007 sn, yine 100bin değer için de tahmin yapmak 0.0009 sn. sürüyor. Modelimiz kötü , R2 değeri 0.5 ama amacımız zaten modelin sonuçları değil , performansını ölçmek.</p><p>Veri sayısını arttırarak denemeler yapalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*mC3WwuPo6NUwpxMdR9KZ8g.png" /><figcaption>10Milyon satır için</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*hI3wevwUQvWkuKsFu0vx5w.png" /><figcaption>20milyon satır için</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*2RVaYAfxDT3dC0cQxXnziw.png" /><figcaption>30Milyon satır için</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*ZjB88thW8b4ClxRi8khR_g.png" /><figcaption>40Milyon satır için</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*dJERYIQKa4ZyXQGpIN3bSQ.png" /><figcaption>100milyon satır için</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4kfUU91XIAkIqZYks5KrA.png" /></figure><p>Data büyüdükçe , modeli eğitme zamanı artarak büyüyor , modelden tahmin etme zamanında artış var model eğitmeye göre çok daha küçük.</p><p>Şimdi bu denemeleri cuML kullanarak GPU’da yapacağız.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import time<br>import cudf<br>from cuml.linear_model import LinearRegression as LRGPU<br>import cupy as cp<br>num=100000<br>w = 20<br>x = np.random.normal(size=(num))<br>b=1<br>y = w*x+b<br>randomdata = np.random.normal(scale=20.0,size=(num))<br>y_randomdata = y+randomdata<br>print(&quot;number  of elements&quot;,num)<br>start_dfcreation = time.perf_counter()<br>df_gpu = cudf.DataFrame({&#39;x&#39;: x, &#39;y&#39;: y_randomdata})<br>end_dfcreation = time.perf_counter()<br>print(f&quot;DataFrame(fit) creation time: {end_dfcreation - start_dfcreation:.6f} seconds&quot;)<br>lrgpu = LRGPU(solver=&#39;svd&#39;)<br><br><br>start_fit = time.perf_counter()<br>lrgpu.fit(df_gpu[[&#39;x&#39;]],df_gpu[&#39;y&#39;])<br>end_fit = time.perf_counter()<br>fit_time = end_fit - start_fit<br>print(f&quot;Fitting time: {fit_time:.6f} seconds&quot;)<br>r2 = lrgpu.score(df_gpu[[&#39;x&#39;]],df_gpu[&#39;y&#39;])<br>print(f&quot;R² score: {r2}&quot;)<br><br>predictinputs = np.linspace(-5,5,num=num)<br>start_dfcreation = time.perf_counter()<br>df_cudf = cudf.DataFrame({&#39;inputs&#39;: predictinputs})<br>end_dfcreation = time.perf_counter()<br>print(f&quot;CUDF (Prediction) DataFrame creation time: {end_dfcreation - start_dfcreation:.6f} seconds&quot;)<br><br><br><br>start_pred = time.perf_counter()<br>predictoutputs = lrgpu.predict(df_cudf[[&quot;inputs&quot;]])<br>end_pred = time.perf_counter()<br>pred_time = end_pred - start_pred<br>print(f&quot;Prediction time: {pred_time:.6f} seconds&quot;)<br><br>plt.scatter(x,y_randomdata,label=&quot;data&quot;)<br>plt.plot(x,y,color=&quot;red&quot;,label=&quot;math.truth&quot;)<br>plt.plot(predictinputs,predictoutputs.to_numpy(),color=&quot;green&quot;,label=&quot;prediction&quot;)<br>plt.legend()<br><br><br><br></pre><p>Hemen hemen aynı kod , ama sklearn yerine cuml kullanıyoruz. cuml ile ML algoritmalarını GPU üzerinde çalıştırıyoruz , cuDF ile de dataframe işlemlerini yine GPU üzerinde yapıyoruz. Yine veri sayısını arttırarak bu kodu çalıştırıyorum :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*fkgiZVaNM1Y95P0UzM9McA.png" /><figcaption>100bin satır data için cuML lineer regresyon sonuçları</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*g4EWTzo1UlcvBeb0R9JVRA.png" /><figcaption>10Milyon satır data için cuML lineer regresyon sonuçları</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*9gha6xMJkdxHFxRC2UzlCQ.png" /><figcaption>20Milyon satır data için cuML lineer regresyon sonuçları</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*0knz8TVzdqRVPuvPkBwCSw.png" /><figcaption>30Milyon satır data için cuML lineer regresyon sonuçları</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*7GKM4MW1YNTwyYlp2sI8Pw.png" /><figcaption>40Milyon satır data için cuML lineer regresyon sonuçları</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*BcpEv1Qo0njq_RSw3_tcDA.png" /><figcaption>50Milyon satır data için cuML lineer regresyon sonuçları</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*R4ZNDWJEOdkHZV9RvHV_aQ.png" /><figcaption>100Milyon satır data için cuML lineer regresyon sonuçları</figcaption></figure><p>Bunları özetleyelim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*T62UfJlrePW3kVgrLZUv-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISinwXRPUz3rF4AHWwBf_A.png" /></figure><p>Veri büyüdükçe , Gpu memorysine veriyi kopyalama zamanı da lineer olarak artıyor ama model calıstırma zamanımız daki artış çok daha az.</p><p>Daha önce yapmış olduğumuz CPU üzerindeki çalıştırmalarımız ile GPU’yu karşılaştıralım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzHTjP3wxJZQSA7tzNapFQ.png" /></figure><p>Veri büyüdükçe , modelin CPU üzerindeki çalışması lineer olarak artıyor , ama GPU’da bu işlem çok daha hızlı gerçekleştiği gibi, verinin büyümesi de CPU’da olduğu gibi sürenin uzamasına neden olmuyor.</p><p>Daha önce olduğu gibi ncu kullanarak nvidia nsight compute ile de 100 milyon satır için inceleme yaptım :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCIBSwbmeYHG0uRcg-nTFg.png" /><figcaption>100milyon satır için GPU üzerinde çalışan lineer regresyonun nsight compute profili</figcaption></figure><p>Bir önceki bölümde, cuDF’in kaynak koduna kadar giderek , yine yukarıdaki çıktıda yeralan her kernel fonksiyonunun ne olduğunu anlamaya çalışmıştım. Bunun yanında ncu cıktısını aldığımız ekranda da her aşamadan sonra ekrana cıktılar koyarak python programında yapmış olduğumuz işlemlerin hangi kernel fonksiyonlarına denk geldiğini bulmuştum. Aynı mantıkla cuML üzerinde de ilerliyorum. 100 milyon satır için en uzun süre 594 msn ile geqr2_gmem_domino kerneli. Bu kernel için detay sayfasına bakalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkjrTRT88mWpwOnq2eCqPA.png" /></figure><p>Bu nokta bana şunu düşündürdü , bu işlem daha fazla parallelik ile çalışsa daha hızlı sonuçlanmayacak mı? Roofline analizi ( detay sayfasında biraz daha aşağıdaki çıktı, aşağıya görselini aldım ) tam da bunu söylüyor. Gpu ‘nun hesaplama kapasitesinin altında kaldığımızı grafikte yer alan turuncu noktanın yerine göre belirliyoruz. Turuncu nokta aşağıda ve eğriden uzakta. Peki bu sonuçla ne yapabiliriz? Bu kernel 512 blocksize ile çalışıyor. ( Özet sayfasında bunu en sağda görebiliyoruz ) Daha önce cuda c ile çalışırken paralellik değerlerini kendimiz ayarlayabiliyorduk ama burada cuML kullanıyoruz , kodu biz değiştirmek istemeyiz, burada duruyorum.(Yine de bunu bir soru olarak Rapidsgithub sayfasında ilettim)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiqM8Qi5hROxeuhCAfmv1g.png" /></figure><p>Böylece yeterli detayda bir ncu analizi yaptığımı düşünüyorum , buna benzer şekilde high level dillerin GPU’yu nasıl kullanıldığını da analiz edebileceğimizi gördüm.</p><p>Bundan sonraki bölümde Dask ile devam edeceğim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28cb2e0161da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are We Using Our GPUs Efficiently? An Introduction to GPU Monitoring and Optimization]]></title>
            <link>https://medium.com/@utolgaevren/are-we-using-our-gpus-efficiently-an-introduction-to-gpu-monitoring-and-optimization-449cd1596d22?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/449cd1596d22</guid>
            <category><![CDATA[gpu-optimization]]></category>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 06:03:01 GMT</pubDate>
            <atom:updated>2025-06-12T06:03:01.419Z</atom:updated>
            <content:encoded><![CDATA[<p>GPUs are expensive and limited resources. Are we truly utilizing them efficiently? In this article, I’ll discuss methods for monitoring and optimizing GPU usage.</p><p>When I started exploring this topic, I asked myself the following questions:</p><ol><li>How can I understand whether the processes running on my GPU are optimized?</li><li>What does optimization on a GPU mean?</li><li>What types of processes can we run on a GPU? Deep learning, ML, data transformation, etc. — which ones are suitable?</li><li>Should I use C CUDA, or PyCUDA / CuPy in Python?</li><li>How can I monitor the GPU performance of my Python code?</li><li>GPU vs. pandas vs. Spark — which performs better?</li></ol><p>In this article, I’ll cover questions 1 and 2; the remaining ones will be explored in my next post.</p><p>Starting simple — writing a C program that only uses GPU memory:</p><pre>#include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br>__global__ void emptyKernel() {<br>    <br>}<br><br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %zu GB\n&quot;, free_mem , free_mem / (1024*1024*1024));<br>    printf(&quot;Total GPU memory: %zu bytes, %zu GB\n&quot;, total_mem ,total_mem / (1024*1024*1024));<br>}<br><br>int main()<br>{<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo();<br><br>    long long total_bytes = 1024LL * 1024 * 1024; <br>    long long num_elements_total = total_bytes / sizeof(int);<br><br>    int blockSize = 1024; <br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br>    <br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br>    printf(&quot;Block size: %d\n&quot;, blockSize);<br>    printf(&quot;Number of blocks: %lld\n&quot;, numBlocks_required);<br>    <br>    emptyKernel&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;();<br>    <br>    cudaError_t kernelError = cudaGetLastError();<br>    if (kernelError != cudaSuccess) {<br>        fprintf(stderr, &quot;Kernel launch failed: %s\n&quot;, cudaGetErrorString(kernelError));<br>    }<br><br>    displayMemoryInfo();<br>    return 0;<br>   <br>}</pre><p>To run this, we compile it using nvcc. I used the following command on Google Colab:</p><p>!nvcc -o testGPUsimple testGPUsimple.cu -arch=sm_75</p><p>This compiles testGPUsimple.cu and generates an executable named testGPUsimple. We can run it directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*-MQ2IbpRH2jCND5v.png" /></figure><p>The result is a simple test program that prints basic GPU memory information. I ran it on a Tesla T4 GPU on Colab.<br> Before diving into details, I profiled this “do nothing” program using ncu (NVIDIA Nsight Compute):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*TPQwmn4UFGXS1uQy.png" /></figure><p>This tool saves GPU metrics to a file named profile1, which we can analyze using NVIDIA Nsight Compute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*CxFK77g_OoSMF_rd.png" /></figure><p><strong>GPU Kernel Basics</strong></p><p>To write GPU code using CUDA, we declare functions with the __global__ keyword in C files (.cu). These functions are called <em>kernels</em> and run on the GPU:</p><pre>__global__ void emptyKernel() {<br>    <br>}</pre><p>The code inside the emptyKernel function is what will be executed on the <strong>GPU</strong>.</p><p>Since GPUs are specifically designed for <strong>parallel processing</strong>, they can execute <strong>independent operations</strong> extremely fast through parallel threads.</p><p><strong>Vector addition</strong> is a great example of this type of simple mathematical operation.<br> (We will implement this example below.)</p><p><strong>Operating system tools</strong> that display GPU usage can only show <strong>basic metrics</strong> — for example, in Windows Task Manager, you can see <strong>GPU utilization percentages</strong>.</p><p>However, <strong>NVIDIA Nsight Compute</strong> provides <strong>a much richer set of metrics</strong>, offering much deeper insight into GPU performance.</p><p>Let’s take a look at the <strong>profile summary</strong> screen of our empty kernel code.<br> Here, we can clearly see the emptyKernel function listed (the term <strong>kernel</strong> refers to these blocks of code executed on the GPU).</p><p>The emptyKernel took <strong>2.89 ms</strong> to run.<br> Just below this, we see that the <strong>Achieved Occupancy</strong> is <strong>42%</strong>, meaning there is room for a <strong>58% improvement</strong>.<br> (Nsight Compute explains these metrics in great detail.)</p><p><strong>Occupancy</strong> is an important metric — it shows <strong>how well the number of blocks and threads we are using matches the GPU architecture</strong>.</p><p>By selecting a <strong>better block size</strong>, we can utilize <strong>more of the GPU’s parallel processing capacity</strong>.</p><p>Occupancy essentially tells us:</p><ul><li>What is the <strong>maximum parallel capacity</strong> of the GPU?</li><li>How many parallel operations (think of these as threads) can be executed at once?</li><li>How many are we currently utilizing?</li></ul><p><strong>Vector Addition Example (Large Scale Parallelism)</strong></p><p>Now, suppose we have <strong>two integer vectors</strong>, and we want to <strong>add them together</strong>.</p><p>Let’s assume these vectors are large — <strong>1 GB each</strong>.<br> If we want to create a 1 GB array of integers in memory:</p><pre>1 GB = 1024 * 1024 * 1024 bytes  <br>1 integer = 4 bytes  <br>=&gt; Number of elements = 1 GB / 4 = 268,435,456 elements </pre><pre>C[i] = A[i] + B[i]</pre><p>These operations are fully independent — calculating C[2] does not depend on C[1] or C[0].</p><p>On a CPU, we would run this serially:</p><pre>for (int i=0; i&lt;268435456; i++) {<br>    C[i] = A[i] + B[i];<br>}</pre><p>Using a GPU, we can run this in parallel with enormous speed-up. In fact, we can launch <strong>268 million parallel threads</strong> for this operation!</p><p>Example kernel:</p><pre>__global__ void simpleVectorAdd(int* A, int* B, int* C, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>        C[idx] = A[idx] + B[idx];<br>    }<br>}</pre><p>Full code:</p><pre> #include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br>// GPU üzerinde vektörü sıfırdan N&#39;e kadar dolduran kernel proc<br>__global__ void initializeVector(int* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx;<br>    }<br>}<br><br>// GPU üzerinde iki vektörü toplayan kernel proc<br>__global__ void simpleVectorAdd(int* A, int* B, int* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] + B[idx] ;<br>        }<br>}<br><br>// GPU memorysi yaratan proc<br>void allocateMemory(int** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}<br><br>// GPU memorysini silen proc<br>void deAllocateMemory(int* d_A) { <br>    cudaError_t err ;<br>    err = cudaFree(d_A);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaFree failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>        <br>    }<br>    printf(&quot;Deallocated GPU memory\n&quot;);<br>}<br><br>// Mevcut ve toplam GPU memorysini gösteren proc<br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %f GB\n&quot;, free_mem , free_mem / (1024.0*1024.0*1024.0));<br>    printf(&quot;Total GPU memory: %zu bytes, %f GB\n&quot;, total_mem ,total_mem / (1024.0*1024.0*1024.0));<br>}<br><br>int main()<br>{<br>    // CUDA cihaz özelliklerini al<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo(); // Bellek durumunu yazdır<br><br>    int* vectorA = nullptr;<br>    int* vectorB = nullptr;<br>    int* vectorC = nullptr;<br><br>    // İşlenecek veri boyutunu belirle (1 GB veri)<br>    long long total_bytes = 1024LL * 1024 * 1024; <br>    long long num_elements_total = total_bytes / sizeof(int);<br><br>    int blockSize = 1024;  // CUDA block boyutu<br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br>    <br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br>    printf(&quot;Block size: %d\n&quot;, blockSize);<br>    printf(&quot;Number of blocks: %lld\n&quot;, numBlocks_required);<br><br>    // CUDA zaman ölçümü için event oluştur<br>    cudaEvent_t start, stop;<br>    float milliseconds=0.0f;<br>    cudaEventCreate(&amp;start);<br>    cudaEventCreate(&amp;stop);<br>    <br>    // Memory allocation için zamanı ölç<br>    cudaEventRecord(start);<br>    allocateMemory(&amp;vectorA, num_elements_total * sizeof(int));<br>    allocateMemory(&amp;vectorB, num_elements_total * sizeof(int));<br>    allocateMemory(&amp;vectorC,num_elements_total * sizeof(int));<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br><br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for GPU global memory allocations: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörlere ilk değerleri ata <br>    cudaEventRecord(start);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the initialization of the vectors: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörleri topla (kernel çalıştır)<br>    cudaEventRecord(start);<br>    simpleVectorAdd&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, vectorB, vectorC, num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the kernel: %f milliseconds\n&quot;,milliseconds);<br><br>    // Kernel hatalarını kontrol et  <br>    cudaError_t kernelError = cudaGetLastError();<br>    if (kernelError != cudaSuccess) {<br>        fprintf(stderr, &quot;Kernel launch failed: %s\n&quot;, cudaGetErrorString(kernelError));<br>    }<br><br>    displayMemoryInfo();<br><br>    // GPU sonuçlarını CPU&#39;ya kopyala<br>    int* vectorA_Cpu = (int*) malloc(num_elements_total * sizeof(int));<br>    int* vectorB_Cpu = (int*) malloc(num_elements_total * sizeof(int));<br>    int* outputforCpu = (int*) malloc(num_elements_total * sizeof(int));<br>    cudaMemcpy(vectorA_Cpu, vectorA, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost); <br>    cudaMemcpy(vectorB_Cpu, vectorB, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost);     <br>    cudaMemcpy(outputforCpu, vectorC, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost); <br>    <br>    // İlk 5 ve son 5 sonucu yazdır<br>    printf(&quot;First 10 and last 10 elements of the output vector:\n&quot;);<br>    for (int i = 0; i &lt; 5; i++) {<br>        printf(&quot;%d + %d = %d\n&quot;, vectorA_Cpu[i],vectorB_Cpu[i],outputforCpu[i]);<br>    }<br>    printf(&quot;\n&quot;);<br>    for (int i = num_elements_total-1; i &gt; num_elements_total-6; i--) {<br>        printf(&quot;%d + %d = %d\n&quot;, vectorA_Cpu[i],vectorB_Cpu[i],outputforCpu[i]);<br>    }<br><br>    printf(&quot;\n&quot;);<br>    deAllocateMemory(vectorA);<br>    deAllocateMemory(vectorB);<br>    deAllocateMemory(vectorC);<br>    free(vectorA_Cpu);<br>    free(vectorB_Cpu);<br>    free(outputforCpu);<br>    //cudaDeviceReset(); <br>    displayMemoryInfo();<br><br>    return 0;<br>   <br>}</pre><p><strong>GPU architecture allows us to configure the number of blocks and threads:</strong></p><p>Both CPUs and GPUs consist of <strong>synchronously operating electronic circuits</strong>.<br> In other words, everything happens in <strong>cycles</strong> that occur at a certain clock frequency.</p><p>The GPU executes operations <strong>in parallel</strong>, simultaneously, and these operations are distributed across the GPU cores as <strong>thousands of small processing groups (called warps)</strong> during each invocation of a <strong>CUDA kernel function</strong>.</p><p>Now, where do we define <strong>how much parallelism</strong> we want?</p><p>When writing a <strong>multithreaded program</strong> in Java or C++, we simply specify the <strong>number of threads</strong>.<br> In GPUs, however, there are <strong>a few more parameters</strong> involved.</p><pre>emptyKernel&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;();</pre><p>We define the level of parallelism by specifying both the <strong>number of blocks</strong> and the <strong>number of threads per block</strong>.</p><p>For example, we could perform the addition of two vectors of <strong>268 million elements</strong> using <strong>1 block with 32 threads</strong>, or <strong>2 blocks with 1024 threads</strong> — it’s up to how we configure it.</p><p>In general, this can be calculated as follows:</p><pre>long long total_bytes = 1024LL * 1024 * 1024; <br>long long num_elements_total = total_bytes / sizeof(int);<br>int blockSize = 1024; <br>long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;</pre><p>For 268 million elements with blockSize = 1024, the required number of blocks is ~262,144.<br> This way, we achieve full parallelism for vector addition.</p><p><strong>Detailed Steps in the Program:</strong><br><strong>Memory Allocation on GPU:</strong></p><pre>allocateMemory(&amp;vectorA, num_elements_total * sizeof(int));</pre><p>Using cudaMalloc, we allocate space on GPU memory.</p><p><strong>Vector Initialization on GPU:</strong></p><pre>initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, num_elements_total);</pre><pre>// GPU üzerinde vektörü sıfırdan N&#39;e kadar dolduran kernel proc<br>__global__ void initializeVector(int* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx;<br>    }<br>}</pre><p>No for-loops required — GPU threads initialize the vector in parallel.</p><p>We are initializing <strong>vectorA</strong> and <strong>vectorB</strong> with values ranging from <strong>0 to N</strong>.</p><p>One interesting point here is that <strong>we do not need to use a for-loop</strong>.<br> The initializeVector kernel is executed on the GPU with the <strong>parallelism defined by </strong><strong>numBlocks_required and </strong><strong>blockSize</strong>.</p><p>Inside the idx variable, we calculate <strong>which thread within which block</strong> is executing, and perform the corresponding operation accordingly.</p><p>The condition idx &lt; num_elements ensures that <strong>we do not perform operations beyond the boundaries of the vector</strong>.</p><p><strong>Vector Addition on GPU:</strong></p><pre>simpleVectorAdd&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, vectorB, vectorC, num_elements_total);</pre><p>Each thread performs one element-wise addition</p><p><strong>Transferring Data Back to CPU:</strong></p><pre>cudaMemcpy(vectorA_Cpu, vectorA, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost);</pre><p>We copy the results back to CPU memory for validation and display.</p><p>Example output (first 5 and last 5 elements of the result vector) confirms correct computation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*wlSWXne0CVGNVbFH.png" /></figure><p>On a Tesla T4 GPU with 14 GB of memory, using a parallel configuration of <strong>1024 × 262,144</strong>, allocating memory for the A, B, and C vectors on the GPU took <strong>0.77 ms</strong>.<br> Filling these vectors with <strong>268 million elements</strong> took <strong>9.22 ms</strong>, and performing the vector addition took <strong>12 ms</strong>.</p><p>In total, adding <strong>268 million elements</strong> took <strong>less than 25 ms</strong>!</p><p>(I measured the execution time of the program — which runs operations on the GPU — using the time command. However, time only measures CPU time, so I disregarded the user and sys times and focused on the real time.</p><p>The real time shows around <strong>2.5 seconds</strong>, but this is misleading — the program also includes data transfer operations from GPU memory to CPU memory, which accounts for much of this time.</p><p>When I removed these memory copy operations from the code and ran time again, here are the results I observed:)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*qZWfJiqBODBn7_xp.png" /></figure><p>As you can see, it took <strong>0.25 ms</strong>.</p><p>For comparison, I also implemented and ran the same operation on the CPU, as shown below:</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;time.h&gt;<br><br>int main() {<br>    // Vektör boyutu<br>    const int N = 268435456;<br><br>    // Vektörler için bellek ayırma<br>    int *a = (int*)malloc(N * sizeof(int));<br>    int *b = (int*)malloc(N * sizeof(int));<br>    int *c = (int*)malloc(N * sizeof(int));<br><br> <br>    clock_t start_time = clock();<br><br>    // a ve b vektörlerini doldurma<br>    for (int i = 0; i &lt; N; i++) {<br>        a[i] = i;<br>        b[i] = i;<br>    }<br><br>    for (int i = 0; i &lt; N; i++) {<br>        c[i] = a[i] + b[i];<br>    }<br><br>   <br>    clock_t end_time = clock();<br><br>    double elapsed_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;<br>    printf(&quot;Islem tamamlama suresi: %f saniye\n&quot;, elapsed_time);<br><br>    // Belleği serbest bırakma<br>    free(a);<br>    free(b);<br>    free(c);<br><br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*wSbOG1BE-x7TYHgf.png" /></figure><p>The same operation performed on the CPU took a total of <strong>3.10 seconds</strong>.</p><p>Now, let’s analyze the profiling results using ncu:</p><p>!ncu — set full -o profile2 ./testgpusimplevectoradd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*I1ocqhrbJlA-qwUW.png" /></figure><p>First of all, on the <strong>summary page</strong>, we can see all <strong>three kernels</strong> listed. The <strong>duration</strong> field shows how long each one took, with a total runtime of <strong>21.49 ms</strong>.<br> (Note: there may be slight differences between these profiling results and the timing measurements we performed in the program — ncu profiling provides more precise measurements for kernels.)</p><p>When we compare this output with our initial example, we see that the <strong>estimated speedup</strong> is around <strong>14.14% and 10%</strong> for each kernel, which are relatively low values.<br> This indicates that we successfully utilized a high degree of parallelism on the GPU.</p><p>Looking at the <strong>Achieved Occupancy</strong> value, we see it is quite high at <strong>89.2%</strong>.</p><p>In summary, according to the profile report, our program effectively leveraged the power of the GPU.</p><p><strong>Memory Bound ? GPU Bound?</strong></p><p>Now, let’s go to the <strong>details page</strong> and examine the output shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*GOzHnBM0YCVnu6Dw.png" /></figure><p>On this screen, we currently focus on two variables: <strong>Compute (SM) Throughput</strong> and <strong>Memory Throughput</strong>. These two variables are also shown in the graph below. Let’s interpret them.</p><p>The <strong>Compute (SM) Throughput</strong> is reported as <strong>23.07%</strong>.<br> This means our program is utilizing <strong>23.07% of the GPU’s total computing power</strong>.</p><p>But earlier, on the previous screen, we saw an <strong>Achieved Occupancy</strong> value of <strong>89%</strong> — meaning we were utilizing parallelism very well.<br> Does this seem contradictory? Not really.</p><p>This is entirely related to the <strong>complexity of the operations we are performing</strong>.<br> We’ve configured the parallelism very well, but the operation itself is very simple — we are simply adding two integers.<br> The GPU is capable of doing much more complex computations, so in this case we are only using <strong>23.07% of its compute capacity</strong>.</p><p>If we made the operation more complex (e.g. multiplication, floating-point operations), this number would increase.<br> In this scenario, our application is <strong>not GPU-bound</strong>.</p><p>Now let’s look at the <strong>Memory (%)</strong> variable.</p><p>Here, we see a value of <strong>89.52%</strong>.<br> Looking at the program output, we know the GPU has <strong>14 GB of memory</strong>, and we are using <strong>3 GB</strong>.<br> So, what does this 89.52% mean?</p><p>It does <strong>not</strong> represent the percentage of total memory used (i.e. it doesn’t mean we are using 89.52% of 14 GB).<br> This value actually measures <strong>GPU memory bandwidth utilization</strong> — in other words, how much of the memory read/write bandwidth we are consuming.</p><p>Our program, through reading and writing operations for <strong>268 million elements</strong>, is saturating <strong>89% of the available bandwidth</strong>.<br> While the GPU cores are much faster than memory access, the simple nature of our computations (basic math) means that <strong>memory throughput becomes the bottleneck</strong> — the program is <strong>memory-bound</strong>.</p><p>Is this a problem?<br> Not really — let’s remember that this program finishes in just <strong>25 ms</strong> — there’s no issue here.</p><p>In short: yes, we are memory-bound, but it’s not a problem in this case.</p><p>Now, let’s scroll further down on the same screen and take a look at the <strong>Compute Workload Analysis</strong> section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*cIsaPxNVDVC4uN41.png" /></figure><p>This screen essentially <strong>confirms what I just explained</strong>.</p><p>As we can see, the GPU is performing <strong>very simple operations</strong>, which is why we see only small percentages in the <strong>ALU</strong> and <strong>FMA</strong> sections.</p><p>The most significant value appears in the <strong>LSU (Load/Store Unit)</strong> section, which indicates <strong>read and write operations to and from GPU memory</strong>.<br> In this case, the program is performing <strong>continuous memory read/write operations</strong>.</p><p>Now, let’s move on to one of my favorite charts in the Nsight Compute interface.<br> If we scroll down a bit further, we will find the <strong>Memory Workload Analysis</strong> chart — let’s take a look at it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*SmvFyaSih0lMcm5M.png" /></figure><p>This chart provides a <strong>detailed view of memory usage on the GPU</strong>.</p><p>On the far right, <strong>Device Memory</strong> represents the <strong>global memory (DRAM)</strong> of the GPU.<br> Right above it, <strong>System Memory</strong> refers to the <strong>RAM</strong> of the host machine.</p><p>When the GPU processor transfers data to and from global memory, it uses <strong>three levels of cache</strong> to speed up these operations.</p><p>The first cache level, closest to the GPU cores, is the <strong>L1/TEX Cache</strong>.</p><p>It is not possible to explicitly control the <strong>L1/TEX Cache</strong> in your program — you cannot directly declare a variable to be placed in the L1/TEX Cache.<br> However, a portion of this cache is allocated as <strong>shared memory</strong>, which <strong>can</strong> be managed by the programmer.</p><p>By placing certain variables in <strong>shared memory</strong>, we can reduce global memory accesses and improve performance.</p><p>Now, could we place the entire <strong>268-million-element dataset</strong> from our example program into shared memory to speed it up?<br> Unfortunately, no — shared memory is only a few kilobytes in size, so it is impossible to store the entire dataset there.</p><p>However, there are techniques for using <strong>shared memory effectively</strong> in certain situations (I will cover these in detail with examples in a future post).</p><p>Now, let’s take a look at the values shown in the chart:</p><p><strong>L1 cache hit ratio = 0%.</strong><br> This means that <strong>none of the data accessed by our program was served from the L1 cache</strong>.<br> In fact, we cannot explicitly manage this cache — for data to enter the cache, it must be accessed in a certain <strong>regular and frequent pattern</strong>.</p><p>Considering that our operation is simply C[i] = A[i] + B[i], where each thread works on <strong>a different data element with no repeated access</strong>, it is perfectly normal that nothing was served from the L1 cache.</p><p>Now, let’s interpret the <strong>L2 cache</strong>:</p><p><strong>L2 cache hit ratio = 33%.</strong><br> The <strong>L2 cache</strong> stores frequently accessed data fetched from global memory and serves it more quickly in subsequent accesses.</p><p>Just like with L1, our access pattern here is also non-repetitive — so why do we see <strong>33% instead of 0%</strong>?</p><p>The reason is that when our program cannot find the needed data in L1, nor initially in L2, it reads the data from <strong>global memory</strong>, which then gets written into L2 cache and subsequently served from there.</p><p>Some of these write operations may be <strong>counted as “hits”</strong> in the graph (even though technically, a cache hit should apply to reads, not writes).<br> That is why we see <strong>33% here</strong>.</p><p>The <strong>yellow bar</strong> to the left of the <strong>Device Memory</strong> box represents <strong>bandwidth utilization</strong>, ranging from <strong>0 to 100</strong> on the right scale.<br> Previously, we mentioned <strong>Memory % = 89.2%</strong> — this yellow bar visually reflects that value.</p><p>We also see <strong>bidirectional arrows</strong> between <strong>Device Memory</strong> and <strong>L2 Cache</strong>, indicating:</p><ul><li><strong>2.36 GB</strong> read from Device Memory to L2 Cache.</li><li><strong>1.20 GB</strong> written from L2 Cache back to Device Memory.</li></ul><p>Given that our operation is C[i] = A[i] + B[i], these numbers make sense — <strong>two reads</strong> (A and B) for every <strong>one write</strong> (C).</p><p>Similarly, we can observe <strong>data transfers between L1/TEX and L2</strong>.</p><p>At this point, I would like to close this section by posing a question:<br> <strong>If there was 2.15 GB of data transferred between L1 and L2, why is the L1 hit ratio still 0%?</strong></p><p>This concludes our initial exploration of <strong>how to analyze GPU performance using NCU and NVIDIA Nsight Compute</strong>.<br> In my next post, I plan to continue by exploring the remaining topics in more detail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=449cd1596d22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are We Getting the Most Out of GPUs? — II]]></title>
            <link>https://medium.com/@utolgaevren/are-we-getting-the-most-out-of-gpus-ii-4931fc7e6018?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4931fc7e6018</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 09:17:10 GMT</pubDate>
            <atom:updated>2025-06-03T09:17:10.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Are We Getting the Most Out of GPUs? — II</p><p>GPUs are high-cost and limited resources. Are we truly utilizing them efficiently and effectively? In this article, I discuss monitoring and optimization methods for GPU usage.</p><p>When I began exploring this topic, I asked myself the following questions:</p><ol><li>How optimized are the operations running on GPUs, and how can I measure it?</li><li>What does optimization on a GPU even mean?</li><li>What kinds of operations can we use on GPUs? Deep learning, machine learning, data transformation — what’s most suitable?</li><li>Should I use CUDA C, or should I go with Python libraries like PyCUDA or CuPy?</li><li>How can I monitor the performance of the code I’ve written using Python on a GPU?</li><li>Which is better for data processing on GPUs: pandas, Spark, or cuDF?</li></ol><p>In the first part of this series, we examined questions 1 and 2. In this second part, we’ll explore more complex operations using CUDA C for those same questions. Then, we’ll shift gears and use Python to compare the performance of pandas and cuDF libraries on both CPUs and GPUs for DataFrame operations.</p><p>In the previous part, we performed a simple vector addition on the GPU and monitored its behavior using tools like ncu and NVIDIA Nsight Compute. We noted that such a simple operation didn’t really push the limits of the GPU. So, let’s make things more complex this time around.</p><ol><li>Let’s replace addition with multiplication.</li><li>Let’s use floats instead of integers for multiplication.</li></ol><h3>Replacing Addition with Multiplication on the GPU</h3><p>In the first section, we replaced addition with multiplication for vectors on the GPU. The code for integer multiplication looked like this:</p><pre>__global__ void simpleVectorMultiply(int* A, int* B, int* C, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>        C[idx] = A[idx] * B[idx];<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*rWJpWA7u3iT07ytXNp9RVQ.png" /></figure><p>When we replaced addition with multiplication for integer arrays, the results were almost identical. The operation didn’t significantly increase the GPU’s workload.</p><h3>Switching to Floating-Point Multiplication</h3><p>Now, let’s see what changes when we use floating-point values instead of integers for multiplication on the GPU. The relevant CUDA C code looks like this:</p><pre>#include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br> __global__ void initializeVector(float* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx*1.0;<br>    }<br>} <br><br><br>// GPU üzerinde iki vektörü toplayan kernel proc<br><br>__global__ void simpleVectorAdd(float* A, float* B, float* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] * B[idx] ;<br>        }<br>}<br><br>// GPU belleği yaratan proc<br>void allocateMemory(float** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}<br><br>// GPU memorysini silen proc<br>void deAllocateMemory(float* d_A) { <br>    cudaError_t err ;<br>    err = cudaFree(d_A);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaFree failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>        <br>    }<br>    printf(&quot;Deallocated GPU memory\n&quot;);<br>}<br><br>// Mevcut ve toplam GPU memorysini gösteren proc<br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %f GB\n&quot;, free_mem , free_mem / (1024.0*1024.0*1024.0));<br>    printf(&quot;Total GPU memory: %zu bytes, %f GB\n&quot;, total_mem ,total_mem / (1024.0*1024.0*1024.0));<br>}<br><br>int main()<br>{<br>    // CUDA cihaz özelliklerini al<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo(); // Bellek durumunu yazdır<br><br>/*<br>    int* vectorA = nullptr;<br>    int* vectorB = nullptr;<br>    int* vectorC = nullptr;<br>*/<br><br>    float* vectorA = nullptr;<br>    float* vectorB = nullptr;<br>    float* vectorC = nullptr;<br><br>    // İşlenecek veri boyutunu belirle (1 GB veri)<br>    long long total_bytes = 1024LL * 1024 * 1024; <br>    long long num_elements_total = total_bytes / sizeof(float);<br>    printf(&quot;sizeoffloat:%zu\n&quot;,sizeof(float));<br><br>    int blockSize = 1024;  // CUDA block boyutu<br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br>    <br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br>    printf(&quot;Block size: %d\n&quot;, blockSize);<br>    printf(&quot;Number of blocks: %lld\n&quot;, numBlocks_required);<br><br>    // CUDA zaman ölçümü için event oluştur<br>    cudaEvent_t start, stop;<br>    float milliseconds=0.0f;<br>    cudaEventCreate(&amp;start);<br>    cudaEventCreate(&amp;stop);<br>    <br>    // Memory allocation için zamanı ölç<br>    cudaEventRecord(start);<br>    allocateMemory(&amp;vectorA, num_elements_total * sizeof(float));<br>    allocateMemory(&amp;vectorB, num_elements_total * sizeof(float));<br>    allocateMemory(&amp;vectorC,num_elements_total * sizeof(float));<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br><br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for GPU global memory allocations: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörlere ilk değerleri ata <br>    cudaEventRecord(start);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the initialization of the vectors: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörleri topla (kernel çalıştır)<br>    cudaEventRecord(start);<br>    simpleVectorAdd&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, vectorB, vectorC, num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the kernel: %f milliseconds\n&quot;,milliseconds);<br><br>    // Kernel hatalarını kontrol et  <br>    cudaError_t kernelError = cudaGetLastError();<br>    if (kernelError != cudaSuccess) {<br>        fprintf(stderr, &quot;Kernel launch failed: %s\n&quot;, cudaGetErrorString(kernelError));<br>    }<br><br>    displayMemoryInfo();<br><br>    // GPU sonuçlarını CPU&#39;ya kopyala<br>    /*int* vectorA_Cpu = (int*) malloc(num_elements_total * sizeof(int));<br>    int* vectorB_Cpu = (int*) malloc(num_elements_total * sizeof(int));<br>    int* outputforCpu = (int*) malloc(num_elements_total * sizeof(int));<br>    cudaMemcpy(vectorA_Cpu, vectorA, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost); <br>    cudaMemcpy(vectorB_Cpu, vectorB, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost);     <br>    cudaMemcpy(outputforCpu, vectorC, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost); <br>    <br>    // İlk 5 ve son 5 sonucu yazdır<br>    printf(&quot;First 10 and last 10 elements of the output vector:\n&quot;);<br>    for (int i = 0; i &lt; 5; i++) {<br>        printf(&quot;%d + %d = %d\n&quot;, vectorA_Cpu[i],vectorB_Cpu[i],outputforCpu[i]);<br>    }<br>    printf(&quot;\n&quot;);<br>    for (int i = num_elements_total-1; i &gt; num_elements_total-6; i--) {<br>        printf(&quot;%d + %d = %d\n&quot;, vectorA_Cpu[i],vectorB_Cpu[i],outputforCpu[i]);<br>    }<br>*/<br>    printf(&quot;\n&quot;);<br>    deAllocateMemory(vectorA);<br>    deAllocateMemory(vectorB);<br>    deAllocateMemory(vectorC);<br>  //  free(outputforCpu);<br>    //cudaDeviceReset(); <br>    displayMemoryInfo();<br><br>    return 0;<br>   <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54Dltw4IE6f09M_21AidpQ.png" /></figure><p>In this case, we noticed that while the overall result didn’t change much, initializing floating-point vectors took longer — jumping from around 9 ms to roughly 29 ms.</p><h3>Profiling the Floating-Point Multiplication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vpGItBwLpP_xSTyp3Doew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJPC5V9mLTZFR1ak2sJc1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsQLw3UD0Y-YjIQaWaCheA.png" /></figure><p>When we profiled this floating-point multiplication using NVIDIA Nsight Compute (ncu), the report showed some noticeable changes:</p><ul><li><strong>Compute Throughput</strong> increased to 77.29%,</li><li><strong>Memory Throughput</strong> decreased to 26%,</li><li>The report flagged the operation as having <strong>Very High Utilization</strong>,</li><li>Interestingly, we also observed a rise in FP64 (double precision) operations.</li></ul><p>Overall, using floats made better use of the GPU’s capacity. The application was now <strong>GPU-bound</strong> rather than <strong>memory-bound</strong>. Was this a problem? Not really — it still completed in milliseconds.</p><h3>Testing Double Precision Multiplication</h3><p>Now, let’s push it even further by using <strong>double precision (double)</strong> variables. While integers and floats use 4 bytes of memory, doubles require 8 bytes. The CUDA C code for initializing and multiplying double vectors is as follows:</p><pre>#include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br>// GPU üzerinde vektörü sıfırdan N&#39;e kadar dolduran kernel proc<br> __global__ void initializeVector(double* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx*1.0;<br>    }<br>}<br><br><br>// GPU üzerinde iki vektörü toplayan kernel proc<br>__global__ void simpleVectorAdd(double* A, double* B, double* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] * B[idx] ;<br>        }<br>}<br><br>// GPU belleği yaratan proc<br>void allocateMemory(double** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}<br><br>// GPU memorysini silen proc<br>void deAllocateMemory(double* d_A) { <br>    cudaError_t err ;<br>    err = cudaFree(d_A);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaFree failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>        <br>    }<br>    printf(&quot;Deallocated GPU memory\n&quot;);<br>}<br><br>// Mevcut ve toplam GPU memorysini gösteren proc<br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %f GB\n&quot;, free_mem , free_mem / (1024.0*1024.0*1024.0));<br>    printf(&quot;Total GPU memory: %zu bytes, %f GB\n&quot;, total_mem ,total_mem / (1024.0*1024.0*1024.0));<br>}<br><br>int main()<br>{<br>    // CUDA cihaz özelliklerini al<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo(); // Bellek durumunu yazdır<br><br>/*<br>    int* vectorA = nullptr;<br>    int* vectorB = nullptr;<br>    int* vectorC = nullptr;<br>*/<br><br>    double* vectorA = nullptr;<br>    double* vectorB = nullptr;<br>    double* vectorC = nullptr;<br><br>    // İşlenecek veri boyutunu belirle (1 GB veri)<br>    long long total_bytes = 1024LL * 1024 * 1024; <br>    long long num_elements_total = total_bytes / sizeof(double);<br>    printf(&quot;sizeoffloat:%zu\n&quot;,sizeof(double));<br><br>    int blockSize = 1024;  // CUDA block boyutu<br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br>    <br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br>    printf(&quot;Block size: %d\n&quot;, blockSize);<br>    printf(&quot;Number of blocks: %lld\n&quot;, numBlocks_required);<br><br>    // CUDA zaman ölçümü için event oluştur<br>    cudaEvent_t start, stop;<br>    float milliseconds=0.0f;<br>    cudaEventCreate(&amp;start);<br>    cudaEventCreate(&amp;stop);<br>    <br>    // Memory allocation için zamanı ölç<br>    cudaEventRecord(start);<br>    allocateMemory(&amp;vectorA, num_elements_total * sizeof(double));<br>    allocateMemory(&amp;vectorB, num_elements_total * sizeof(double));<br>    allocateMemory(&amp;vectorC,num_elements_total * sizeof(double));<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br><br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for GPU global memory allocations: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörlere ilk değerleri ata <br>    cudaEventRecord(start);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the initialization of the vectors: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörleri topla (kernel çalıştır)<br>    cudaEventRecord(start);<br>    simpleVectorAdd&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, vectorB, vectorC, num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the kernel: %f milliseconds\n&quot;,milliseconds);<br><br>    // Kernel hatalarını kontrol et  <br>    cudaError_t kernelError = cudaGetLastError();<br>    if (kernelError != cudaSuccess) {<br>        fprintf(stderr, &quot;Kernel launch failed: %s\n&quot;, cudaGetErrorString(kernelError));<br>    }<br><br>    displayMemoryInfo();<br><br><br>    printf(&quot;\n&quot;);<br>    deAllocateMemory(vectorA);<br>    deAllocateMemory(vectorB);<br>    deAllocateMemory(vectorC);<br>  //  free(outputforCpu);<br>    //cudaDeviceReset(); <br>    displayMemoryInfo();<br><br>    return 0;<br>   <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIHWjP_HeNnBF2XWYU2tDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oM0cBXQdX7HGLn24M_y4TA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_s3Wbj5NC8IQ5wEWzNcm5w.png" /></figure><p>Since doubles occupy 8 bytes each, we processed half as many elements — about 134 million — for 1GB of memory. Still, ComputeSM was at 62%. To maintain the same conditions, let’s process 268 million elements here as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IKX3kq_VbXdUU7FzllVSg.png" /></figure><p>When we performed the same operation with 268 million double elements (half the amount compared to the float version for the same 1GB memory), the kernel runtime increased to 24 ms, compared to 12 ms for the float version.</p><p><strong>Moving to Matrix Multiplication</strong></p><p>Let’s make things even more complex by testing <strong>matrix multiplication</strong> on the GPU. Unlike vector operations, matrix multiplication involves each element being used multiple times, which introduces <strong>L1 cache</strong> utilization and other GPU memory optimizations. The CUDA C code for the matrix multiplication kernel looks like this:</p><pre>#include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br>// Mevcut vektörleri initialize eden kernel<br>__global__ void initializeVector(double* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx * 1.0;<br>    }<br>}<br><br>// Mevcut vektör toplama kernel<br>__global__ void simpleVectorAdd(double* A, double* B, double* C, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>        C[idx] = A[idx] * B[idx];<br>    }<br>}<br><br>// 🚀 Eklenen yeni matris çarpma kernel (NxN double matrix)<br>__global__ void matrixMultiplyKernel(const double* A, const double* B, double* C, int N) {<br>    int row = blockIdx.y * blockDim.y + threadIdx.y;<br>    int col = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (row &lt; N &amp;&amp; col &lt; N) {<br>        double sum = 0;<br>        for (int k = 0; k &lt; N; ++k) {<br>            sum += A[row * N + k] * B[k * N + col];<br>        }<br>        C[row * N + col] = sum;<br>    }<br>}<br><br>// Mevcut bellek yönetim procları<br>void allocateMemory(double** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}<br>void deAllocateMemory(double* d_A) { <br>    cudaError_t err ;<br>    err = cudaFree(d_A);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaFree failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>    }<br>    printf(&quot;Deallocated GPU memory\n&quot;);<br>}<br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %f GB\n&quot;, free_mem , free_mem / (1024.0*1024.0*1024.0));<br>    printf(&quot;Total GPU memory: %zu bytes, %f GB\n&quot;, total_mem ,total_mem / (1024.0*1024.0*1024.0));<br>}<br><br>int main() {<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo();<br><br>    // Vektör boyutu: ~2 GB<br>    long long total_bytes = 1024LL * 1024 * 1024 * 2; <br>    //long long num_elements_total = total_bytes / sizeof(double);<br>    int N = 4096;<br>    long long num_elements_total = (long long)N * N;<br>    printf(&quot;sizeofdouble:%zu\n&quot;, sizeof(double));<br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br><br>  <br><br>    int blockSize = 1024;<br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br><br>    cudaEvent_t start, stop;<br>    float milliseconds=0.0f;<br>    cudaEventCreate(&amp;start);<br>    cudaEventCreate(&amp;stop);<br><br>    // Memory allocation<br>    double *vectorA = nullptr, *vectorB = nullptr, *vectorC = nullptr;<br>    allocateMemory(&amp;vectorA, num_elements_total * sizeof(double));<br>    allocateMemory(&amp;vectorB, num_elements_total * sizeof(double));<br>    allocateMemory(&amp;vectorC, num_elements_total * sizeof(double));<br><br>    // Initialize vectors<br>    cudaEventRecord(start);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;Initialization time: %f ms\n&quot;, milliseconds);<br><br>    // 🚀 Matrix multiplication (NxN with N ~ 16384)<br>    //int N = 4096; //16384;<br>    dim3 threadsPerBlock(16,16);<br>    dim3 blocksPerGrid((N+threadsPerBlock.x-1)/threadsPerBlock.x,<br>                       (N+threadsPerBlock.y-1)/threadsPerBlock.y);<br><br>    cudaEventRecord(start);<br>    matrixMultiplyKernel&lt;&lt;&lt;blocksPerGrid, threadsPerBlock&gt;&gt;&gt;(vectorA, vectorB, vectorC, N);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;Matrix multiplication time: %f ms\n&quot;, milliseconds);<br><br>    deAllocateMemory(vectorA);<br>    deAllocateMemory(vectorB);<br>    deAllocateMemory(vectorC);<br>    displayMemoryInfo();<br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*9hYcfeQSDwderMveziDF4g.png" /></figure><p>When we ran this with two 16-million-element matrices on a <strong>Tesla T4 GPU</strong>, the operation took <strong>790 ms</strong>. On an <strong>NVIDIA A100 GPU</strong>, the same operation was <strong>10 times faster:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*PaICOQTm7kmPmkMbyjz0aA.png" /></figure><h3>A100 vs T4 Comparison</h3><p>So, why was the A100 GPU able to perform the same matrix multiplication <strong>10 times faster</strong> than the T4? The <strong>Nsight Compute (ncu)</strong> reports provided some answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQokiQG6JQI78Heiwc2y2w.png" /><figcaption>T4 NCU REPORT</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3rhsozKxM8ZkqQwPm-jiw.png" /><figcaption>A100 NCU REPORT</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fslhZqBTkI7AyafOq8h7A.png" /></figure><ul><li>On the <strong>T4 GPU</strong>, the matrix multiplication kernel achieved a <strong>Compute Throughput</strong> of 96.76% and a <strong>Memory Throughput</strong> of 24%, indicating that the operation was <strong>GPU-bound</strong>. This means we were pushing the compute units to their limits, but memory usage wasn’t optimal.</li><li>On the <strong>A100 GPU</strong>, with significantly higher computational capacity, the Compute Throughput was lower than T4’s (because we couldn’t fully saturate it), but Memory Throughput was higher, indicating a <strong>Memory-bound</strong> scenario. The operation utilized <strong>L1 cache</strong> fully and reduced the number of cycles dramatically — from <strong>887 million</strong> on T4 to <strong>82 million</strong> on A100.</li></ul><p>Thus, <strong>A100’s superior compute and memory architecture</strong> allowed for much faster execution. While on T4, further memory optimizations wouldn’t help (since it’s already compute-bound), on A100, we could improve performance by optimizing shared memory usage.</p><p>With this example, I’m wrapping up the CUDA C analysis. From here, I’ll move on to higher-level frameworks (Python, cuDF) for further exploration.</p><p><strong>Using cuPy:</strong></p><p>Let’s first write a program in Python using cuPy to multiply two matrices on the GPU.</p><pre>import cupy as cp<br>import time<br><br># Matrix boyutu (NxN)<br>N = 4096<br>num_elements = N * N<br>element_size = cp.dtype(cp.float64).itemsize<br>total_bytes = num_elements * element_size<br><br>print(f&quot;Matrix size: {N}x{N}&quot;)<br>print(f&quot;Total elements: {num_elements}&quot;)<br>print(f&quot;Total bytes: {total_bytes / (1024 ** 3):.2f} GB&quot;)<br><br># Bellek durumu göster<br>free_mem, total_mem = cp.cuda.runtime.memGetInfo()<br>print(f&quot;Free GPU memory: {free_mem / (1024**3):.2f} GB&quot;)<br>print(f&quot;Total GPU memory: {total_mem / (1024**3):.2f} GB&quot;)<br><br># Bellek ayırma ve zaman ölçümü<br>start_time = time.time()<br>A = cp.empty((N, N), dtype=cp.float64)<br>B = cp.empty((N, N), dtype=cp.float64)<br>C = cp.empty((N, N), dtype=cp.float64)<br>cp.cuda.Device().synchronize()<br>alloc_time = time.time() - start_time<br>print(f&quot;Memory allocation time: {alloc_time * 1000:.3f} ms&quot;)<br><br># Matrisleri doldurma<br>start_time = time.time()<br>A = cp.arange(num_elements, dtype=cp.float64).reshape((N, N))<br>B = cp.arange(num_elements, dtype=cp.float64).reshape((N, N))<br>cp.cuda.Device().synchronize()<br>init_time = time.time() - start_time<br>print(f&quot;Initialization time: {init_time * 1000:.3f} ms&quot;)<br><br># Matris çarpımı<br>start_time = time.time()<br>C = cp.dot(A, B)<br>cp.cuda.Device().synchronize()<br>mul_time = time.time() - start_time<br>print(f&quot;Matrix multiplication time: {mul_time * 1000:.3f} ms&quot;)<br><br># GPU sonuçlarını CPU&#39;ya kopyala ve örnek yazdır<br>C_cpu = cp.asnumpy(C)<br>print(f&quot;C[0,0]: {C_cpu[0,0]}&quot;)<br>print(f&quot;C[-1,-1]: {C_cpu[-1,-1]}&quot;)<br><br># Bellek durumu göster<br>free_mem, total_mem = cp.cuda.runtime.memGetInfo()<br>print(f&quot;Free GPU memory after: {free_mem / (1024**3):.2f} GB&quot;)<br>print(f&quot;Total GPU memory: {total_mem / (1024**3):.2f} GB&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*9adcsJkNIaXpKvdJtcT5cA.png" /></figure><p>Compared to the same code written in C, the Python cuPy version took a bit longer to run, mainly due to the differences between the two languages. When using Python cuPy, we deal with far fewer details compared to C — as you can see, we simply used cp.dot(A, B) to perform the operation, without having to worry about memory allocation and other low-level tasks. If we want more control, C is the way to go. But if we want faster development, Python is preferable. Since the profiling reports with cuPy are very similar, I skipped the Nsight Compute (ncu) analysis for the cuPy code.</p><p>Now, let’s look at data frame operations. Let’s start by performing a data query using <strong>pandas</strong> on the CPU.</p><pre>import pandas as pd<br>import time<br><br># Örnek veri oluşturalım<br>data = {<br>    &#39;id&#39;: range(1000000),  # 10 milyon satır<br>    &#39;value1&#39;: range(1000000),<br>    &#39;value2&#39;: [x % 10 for x in range(1000000)]<br>}<br><br>start = time.time()<br># Pandas DataFrame (CPU üzerinde)<br>df = pd.DataFrame(data)<br>end = time.time()<br>print(f&quot;Dataframe creation time: {end - start:.4f} seconds&quot;)<br><br># Zaman ölçümü başlat<br>start = time.time()<br><br># SELECT * FROM df WHERE value2 = 5<br>filtered = df[df[&#39;value2&#39;] == 5]<br><br># SELECT COUNT(*) FROM filtered<br>count = filtered.shape[0]<br><br># SELECT value2, COUNT(*) FROM df GROUP BY value2<br>grouped = df.groupby(&#39;value2&#39;).size()<br><br># Zaman ölçümü bitir<br>end = time.time()<br><br>print(f&quot;Filtered count: {count}&quot;)<br>print(&quot;Group by result:\n&quot;, grouped)<br>print(f&quot;Execution time: {end - start:.4f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*4T-BnTQlOajjXXlOF2hAGQ.png" /></figure><p>Creating the data frame for 1 million records took 0.2 seconds, and the filtering, counting, and group by operations took 0.02 seconds.</p><p>Let’s perform the same operation using <strong>cuDF (CUDA DataFrame)</strong> on the GPU:</p><pre>import cudf<br>import time<br><br># Örnek veri oluşturalım<br>data = {<br>    &#39;id&#39;: range(1000000),  # 1 milyon satır<br>    &#39;value1&#39;: range(1000000),<br>    &#39;value2&#39;: [x % 10 for x in range(1000000)]<br>}<br><br>start = time.time()<br># Pandas benzeri DataFrame ama GPU üzerinde<br>gdf = cudf.DataFrame(data)<br><br>end = time.time()<br>print(f&quot;Dataframe creation time: {end - start:.4f} seconds&quot;)<br><br># Profil için zaman ölçümü başlat<br>start = time.time()<br><br># SELECT * FROM gdf WHERE value2 = 5<br>filtered = gdf[gdf[&#39;value2&#39;] == 5]<br><br># SELECT COUNT(*) FROM filtered<br>count = filtered.shape[0]<br><br># SELECT value2, COUNT(*) FROM gdf GROUP BY value2<br>grouped = gdf.groupby(&#39;value2&#39;).size()<br><br># Profil için zaman ölçümü bitir<br>end = time.time()<br><br>print(f&quot;Filtered count: {count}&quot;)<br>print(&quot;Group by result:\n&quot;, grouped)<br>print(f&quot;Execution time: {end - start:.4f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*ansB9eZRJ7V7XS-ltklvvA.png" /></figure><p>When we perform the same operations on the GPU for 1 million records, creating the data frame takes 0.17 seconds, and the query operations take 0.04 seconds. The completion times are almost the same.</p><p>Now, let’s increase the data size and use 10 million records instead of 1 million.</p><p>Results on the CPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*wXLVIkNTBxUyHU_56Q0Dcg.png" /></figure><p>Results on the GPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*EFDxKjMDLw2PAfZDwzNvJQ.png" /></figure><p>When we increased the data to 10 million records, the processing time on the CPU was 0.25 seconds, while on the GPU it was only 0.05 seconds. The GPU delivered better results for 10 million records.</p><p>Let’s try with 100 million records:</p><p>I first ran it on the CPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*pKXidOE93gFb4sMGu7Y0Mw.png" /></figure><p>Results on the GPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*D4xnW2lCpgePLcxluQnAOQ.png" /></figure><p>I summarized the results from different runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtHCIwhHVsgcPSV818iW3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oWe4iHFaU5QSSQ3JqihaQ.png" /></figure><p>The situation we observe in the table is this: when the number of records is low, performing DataFrame queries on the CPU or GPU yields almost the same performance. However, as the number of records increases, both DataFrame creation and query execution are significantly faster on the GPU. For 100 million records, creating the DataFrame on the GPU is <strong>3.5 times faster</strong> than creating it with pandas on the CPU, and querying is <strong>15 times faster</strong>! Now, let’s dive into the detailed Nsight Compute (ncu) report for the 100 million record case:</p><p>!ncu — set full — target-processes all -o report1 python cudf1.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47gPWBAhnRr_X4vLzs5meg.png" /></figure><p>From the ncu profile we generated with cuDF, we can see that many more kernels are created compared to the tests we’ve done so far. In our earlier custom programs, we named the kernels ourselves, which made it easy to examine what each kernel was doing. However, in these examples where we’re using libraries like cuDF, we don’t control the kernel names. Additionally, we can’t easily map the operations in the Python code to the corresponding kernels. In the output above, we can’t clearly identify which kernel is responsible for creating the DataFrame on the GPU, or which ones are handling the count and group by operations. So, what can we do?</p><p>At this point, since cuDF is an open-source library developed under NVIDIA’s RAPIDS Acceleration, I examined these kernel functions by looking through the code on GitHub (<a href="https://github.com/rapidsai/cudf">https://github.com/rapidsai/cudf</a>). I searched for function definitions starting with __global__ throughout the code repository. After all, for CUDA C-developed functions to run on the GPU, they must include __global__ declarations. After a few searches, I found an example: the single_threaded_kernel function in cpp/include/cudf/detail/utilities/cuda.cuh.</p><pre>CUDF_KERNEL void single_thread_kernel(F f)</pre><p>As you can see, instead of __global__, the CUDF_KERNEL macro is used at the beginning. When I looked into it, I found that this macro also defines __global__.</p><p>Similarly, I found the copy_range_kernel function, and I’ll include its initial part below:</p><pre>CUDF_KERNEL void copy_range_kernel(SourceValueIterator source_value_begin,<br>                                   SourceValidityIterator source_validity_begin,<br>                                   cudf::mutable_column_device_view target,<br>                                   cudf::size_type target_begin,<br>                                   cudf::size_type target_end,<br>                                   cudf::size_type* __restrict__ const null_count)</pre><p>By continuing this investigation, we can further understand what cuDF and similar libraries do under the hood. For example, I wondered:</p><p>In previous examples, when we used C, we created space for data in GPU memory with cudaMalloc and wrote a kernel to fill in the data fields (like the code where we set initial values for 268 million vectors). But how does cuDF handle this process?</p><p>If we weren’t using cuDF, we would first read the data from a database or similar source, then allocate GPU memory with cudaMalloc, and finally, populate the data fields in GPU memory in parallel for each record.</p><p>As an example, I looked at the code in <a href="https://github.com/rapidsai/cudf/blob/branch-24.06/python/cudf/core/dataframe.py">https://github.com/rapidsai/cudf/blob/branch-24.06/python/cudf/core/dataframe.py</a>, which contains GPU counterparts for many DataFrame operations. Additionally, instead of allocating separate memory on the GPU for each DataFrame, it creates a memory pool, among other optimizations.</p><p>However, I couldn’t find an answer to my fundamental question: <strong>Which kernel is used for which cuDF operation?</strong> I wanted to understand this so that I could analyze the ncu report more effectively—knowing how the GPU was used for DataFrame creation, count, and other operations. But I couldn’t find this information.</p><p>To understand this better, I modified the code to include a print statement at the end of each stage. This way, while running ncu, I could clearly identify which kernel functions were being executed at each stage.</p><pre>import cudf<br>import time<br><br># Örnek veri oluşturalım<br>data = {<br>    &#39;id&#39;: range(10000000),  # 10 milyon satır<br>    &#39;value1&#39;: range(10000000),<br>    &#39;value2&#39;: [x % 10 for x in range(10000000)]<br>}<br><br>start = time.time()<br># Pandas benzeri DataFrame ama GPU üzerinde<br>gdf = cudf.DataFrame(data)<br><br>end = time.time()<br>print(f&quot;Dataframe creation time: {end - start:.4f} seconds&quot;)<br><br># Profil için zaman ölçümü başlat<br>start = time.time()<br><br># SELECT * FROM gdf WHERE value2 = 5<br>filtered = gdf[gdf[&#39;value2&#39;] == 5]<br><br>end = time.time()<br>print(f&quot;Execution  for filter: {end - start:.4f} seconds&quot;)<br><br># SELECT COUNT(*) FROM filtered<br>start = time.time()<br>count = filtered.shape[0]<br>end = time.time()<br>print(f&quot;Execution  for count: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br># SELECT value2, COUNT(*) FROM gdf GROUP BY value2<br>grouped = gdf.groupby(&#39;value2&#39;).size()<br>end = time.time()<br>print(f&quot;Execution  for groupby: {end - start:.4f} seconds&quot;)<br><br># Profil için zaman ölçümü bitir<br><br>print(f&quot;Filtered count: {count}&quot;)<br>print(&quot;Group by result:\n&quot;, grouped)<br>#print(f&quot;Execution time: {end - start:.4f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAsHqpyOmJB5dFA7B8wwUA.png" /></figure><p>Now, the ncu output has become much more meaningful. The first 5 kernels are invoked for creating the DataFrame, followed by 9 kernels for the filter operation. There’s no kernel call for the count operation, but for group by, kernels starting with count_set_bits_kernel are triggered. By examining the ncu report this way, we can understand how our code is using the GPU for each operation.</p><p>At this point, I asked myself: what can we do if, after this analysis, we find problems with GPU occupancy or determine that some operations are GPU-bound while others are memory-bound? Previously, when writing our own CUDA code (whether in C or Python), we could intervene by adjusting block size, number of blocks, shared memory usage, and so on. However, with libraries like cuDF, all of these operations are handled internally by the library, making it difficult for us to intervene. While it’s possible to dive into the library’s source code and make changes, we generally don’t want to do that. So, my conclusion is that we can analyze and understand how things work, which may allow us to make some decisions about data reading and processing strategies. However, we can’t fine-tune GPU-level optimizations.</p><p>Now, let’s create a star schema and examine the differences in join performance between the CPU and GPU.</p><p>First, I’m creating a simple star schema using pandas on the CPU and joining a 10-million-row fact table with all dimension tables:</p><pre>import pandas as pd<br>import numpy as np<br>import time<br><br># 🌟 Dimension Tables<br>n_customers = 100000<br>n_products = 10000<br>n_times = 365<br>n_branches = 100<br><br>start = time.time()<br>dim_customer = pd.DataFrame({<br>    &#39;customer_id&#39;: np.arange(n_customers),<br>    &#39;customer_name&#39;: [&#39;Customer_&#39; + str(i) for i in range(n_customers)],<br>    &#39;region&#39;: np.random.choice([&#39;East&#39;, &#39;West&#39;, &#39;North&#39;, &#39;South&#39;], n_customers)<br>})<br>end = time.time()<br>print(f&quot;Dimension Customer creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_product = pd.DataFrame({<br>    &#39;product_id&#39;: np.arange(n_products),<br>    &#39;product_name&#39;: [&#39;Product_&#39; + str(i) for i in range(n_products)],<br>    &#39;category&#39;: np.random.choice([&#39;A&#39;, &#39;B&#39;, &#39;C&#39;], n_products)<br>})<br>end= time.time()<br>print(f&quot;Dimension Product creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_time = pd.DataFrame({<br>    &#39;time_id&#39;: np.arange(n_times),<br>    &#39;date&#39;: pd.to_datetime(np.arange(n_times), unit=&#39;D&#39;, origin=&#39;2022-01-01&#39;),<br>    &#39;year&#39;: 2022 + (np.arange(n_times) // 365)<br>})<br>end= time.time()<br>print(f&quot;Dimension Time creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_branches = pd.DataFrame({<br>    &#39;branch_id&#39;: np.arange(n_branches),<br>    &#39;branch_name&#39;: [&#39;Branch_&#39; + str(i) for i in range(n_branches)],<br>    &#39;city&#39;: np.random.choice([&#39;CityA&#39;, &#39;CityB&#39;, &#39;CityC&#39;], n_branches)<br>})<br><br>end= time.time()<br>print(f&quot;Dimension Branches creation time: {end - start:.4f} seconds&quot;)<br><br>n_transactions = 10000000<br><br>start = time.time()<br>fact_transactions = pd.DataFrame({<br>    &#39;transaction_id&#39;: np.arange(n_transactions),<br>    &#39;customer_id&#39;: np.random.randint(0, n_customers, n_transactions),<br>    &#39;product_id&#39;: np.random.randint(0, n_products, n_transactions),<br>    &#39;time_id&#39;: np.random.randint(0, n_times, n_transactions),<br>    &#39;branch_id&#39;: np.random.randint(0, n_branches, n_transactions),<br>    &#39;amount&#39;: np.random.random(n_transactions) * 100,<br>    &#39;quantity&#39;: np.random.randint(1, 10, n_transactions)<br>})<br><br>end= time.time()<br>print(f&quot;Fact Transactions creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>joined = fact_transactions.merge(dim_customer, on=&#39;customer_id&#39;)\<br>    .merge(dim_product, on=&#39;product_id&#39;)\<br>    .merge(dim_time, on=&#39;time_id&#39;)\<br>    .merge(dim_branches, on=&#39;branch_id&#39;)<br><br>end = time.time()   <br>print(f&quot;Join operation time: {end - start:.4f} seconds&quot;)<br><br>print(f&quot;Joined DataFrame has {len(joined)} rows and {len(joined.columns)} columns.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*Owp4U05av8-wsXEovTpgOg.png" /></figure><p>cudf code:</p><pre>import cudf<br>import cupy as cp<br>import numpy as np<br>import time<br>import pandas as pd<br><br># 🌟 Dimension Tables<br>n_customers = 100000<br>n_products = 10000<br>n_times = 365<br>n_branches = 100<br><br>start = time.time()<br>dim_customer = cudf.DataFrame({<br>    &#39;customer_id&#39;: cp.arange(n_customers),<br>    &#39;customer_name&#39;: [&#39;Customer_&#39; + str(i) for i in range(n_customers)],<br>    &#39;region&#39;: np.random.choice([&#39;East&#39;, &#39;West&#39;, &#39;North&#39;, &#39;South&#39;], n_customers)<br>})<br>end = time.time()<br>print(f&quot;Dimension Customer creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_product = cudf.DataFrame({<br>    &#39;product_id&#39;: cp.arange(n_products),<br>    &#39;product_name&#39;: [&#39;Product_&#39; + str(i) for i in range(n_products)],<br>    &#39;category&#39;: np.random.choice([&#39;A&#39;, &#39;B&#39;, &#39;C&#39;], n_products)<br>})<br>end= time.time()<br>print(f&quot;Dimension Product creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br><br>n_times = 1000   <br>start_date = pd.Timestamp(&#39;2022-01-01&#39;)<br><br>date_series = cudf.Series(start_date + pd.to_timedelta(cp.arange(n_times).get(), unit=&#39;D&#39;))<br><br>dim_time = cudf.DataFrame({<br>    &#39;time_id&#39;: cp.arange(n_times),<br>    &#39;date&#39;: date_series,<br>    &#39;year&#39;: 2022 + (cp.arange(n_times) // 365)<br>})<br><br><br><br><br>end= time.time()<br>print(f&quot;Dimension Time creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_branches = cudf.DataFrame({<br>    &#39;branch_id&#39;: cp.arange(n_branches),<br>    &#39;branch_name&#39;: [&#39;Branch_&#39; + str(i) for i in range(n_branches)],<br>    &#39;city&#39;: np.random.choice([&#39;CityA&#39;, &#39;CityB&#39;, &#39;CityC&#39;], n_branches)<br>})<br>end= time.time()<br>print(f&quot;Dimension Branches creation time: {end - start:.4f} seconds&quot;)<br><br>n_transactions = 10000000   <br><br>start=  time.time()<br>fact_transactions = cudf.DataFrame({<br>    &#39;transaction_id&#39;: cp.arange(n_transactions),<br>    &#39;customer_id&#39;: cp.random.randint(0, n_customers, n_transactions),<br>    &#39;product_id&#39;: cp.random.randint(0, n_products, n_transactions),<br>    &#39;time_id&#39;: cp.random.randint(0, n_times, n_transactions),<br>    &#39;branch_id&#39;: cp.random.randint(0, n_branches, n_transactions),<br>    &#39;amount&#39;: cp.random.random(n_transactions) * 100,<br>    &#39;quantity&#39;: cp.random.randint(1, 10, n_transactions)<br>})<br>end= time.time()<br>print(f&quot;Fact Transactions creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>joined = fact_transactions.merge(dim_customer, on=&#39;customer_id&#39;)\<br>    .merge(dim_product, on=&#39;product_id&#39;)\<br>    .merge(dim_time, on=&#39;time_id&#39;)\<br>    .merge(dim_branches, on=&#39;branch_id&#39;)<br>end = time.time()   <br>print(f&quot;Join operation time: {end - start:.4f} seconds&quot;)<br><br>print(f&quot;Joined DataFrame has {len(joined)} rows and {len(joined.columns)} columns.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*IXrNVkO8hBzVMCpqPpCT0Q.png" /></figure><p>For 10 million records, the join operation took 8 seconds on the CPU but only 0.3 seconds on the GPU. As we increase the number of records, the GPU performs significantly better than the CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZTBKfw_V5_fyyMjOpIRbg.png" /></figure><p>In this second part of the series, we explored how to carry out more complex operations and conduct performance analysis to fully harness the power of GPUs. While the first part focused on simple vector operations, this part covered:</p><ul><li>Performing more complex operations with integer, float, and double data types using CUDA C, and analyzing matrix multiplication.</li><li>Comparing performance differences between different GPU architectures (T4 vs A100), including Compute and Memory Throughput metrics and kernel performance.</li><li>Simplifying GPU data processing by using high-level Python libraries like cuPy and cuDF, thus reducing the complexity of CUDA C.</li><li>Comparing pandas and cuDF to evaluate CPU vs GPU performance across varying data sizes, clearly demonstrating the advantages of GPUs for large datasets.</li><li>Analyzing ncu reports to determine how different operations utilize the GPU, identify bottlenecks, and uncover optimization opportunities.</li></ul><p>In conclusion, data size and algorithm complexity play a major role in GPU utilization. While CPU and GPU performance are similar for small datasets, the advantage of GPUs becomes increasingly apparent as data size grows. CUDA C offers low-level control, while high-level libraries like cuPy and cuDF enable faster and more practical coding. However, for kernel-level optimization, it is still important to examine source code and analyze profiling reports in detail.</p><p>In the third part of this series, we will explore <strong>cuML for machine learning algorithms</strong> and <strong>DASK for distributed GPU memory usage</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4931fc7e6018" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPU’ların Hakkını Veriyor muyuz? — II]]></title>
            <link>https://medium.com/@utolgaevren/gpular%C4%B1n-hakk%C4%B1n%C4%B1-veriyor-muyuz-ii-c21dd78dcf43?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21dd78dcf43</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 08:25:24 GMT</pubDate>
            <atom:updated>2025-06-03T08:25:24.897Z</atom:updated>
            <content:encoded><![CDATA[<p>GPU’ların Hakkını Veriyor muyuz? — II</p><p>GPU’lar yüksek maliyetli ve sınırlı kaynaklar. Acaba GPU’ları verimli ve etkin bir şekilde kullanıyor muyuz? Bu yazıda GPU kullanımının izlenme ve optimizasyon yöntemlerinden bahsediyorum.</p><p>Bu konuyu incelemeye başladığımda şu soruları sordum:</p><p>1. GPU’larda çalıştırılan işlemler ne kadar optimize çalışıyor nasıl anlayabilirim?</p><p>2. GPU’da optimizasyon yapmak ne demek?</p><p>3. GPU’da ne tür işlemleri kullanabiliyoruz? Deep learning , Ml , data transformation vb. hangisi uygun?</p><p>4. C Cuda mı kullanmalıyım , yoksa Pythonda PyCUDA veya CuPy mı?</p><p>5. Python’da GPU kullanarak yazdığım kodun GPU performansını nasıl görebilirim?</p><p>6. GPU , pandas,spark hangisi daha iyi?</p><p>İlk bölümde 1 ve 2.maddeleri incelemiştik. Bu bölümde cuda c ile 1.ve 2. Maddelerdeki işlemleri daha karmaşık hale getireceğiz. Sonra da c yerine Python kullanarak pandas ile cuDF kütüphanelerinin CPU ve GPU performanslarını dataframeler üzerinde inceleyeceğiz.</p><p>Daha önceki bölümde GPU üzerinde 2 vektörü toplama işlemini yapmış ve bu işlem sırasında GPU üzerinde neler olduğunu ncu ve nvidia nsight compute araçları ile izlemiştik. Geçen bölümde toplama işleminin GPU için çok basit olduğunu, bu yüzden de GPU kapasitesini zorlayamadığımızı belirtmiştik. Bu bölüme öncelikle daha karmaşık işlemleri deneyerek başlayalım.</p><p>1. Toplama yerine çarpma yapalım</p><p>2. Integer yerine float kullanarak çarpma yapalım</p><pre>__global__ void simpleVectorMultply(int* A, int* B, int* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] * B[idx] ;<br>        }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*rWJpWA7u3iT07ytXNp9RVQ.png" /><figcaption>GPU üzerinde çalışan integer çarpma işlemi</figcaption></figure><p>Integer’ları toplamak yerine çarpınca pek bir değişiklik olmadı hemen hemen toplama ile aynı sonçları aldık. Şimdi Float değerleri kullanarak çarpma işlemi yaptığımızda neler değişiyor onu inceleyelim.</p><pre>#include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br> __global__ void initializeVector(float* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx*1.0;<br>    }<br>} <br><br><br>// GPU üzerinde iki vektörü toplayan kernel proc<br><br>__global__ void simpleVectorAdd(float* A, float* B, float* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] * B[idx] ;<br>        }<br>}<br><br>// GPU belleği yaratan proc<br>void allocateMemory(float** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}<br><br>// GPU memorysini silen proc<br>void deAllocateMemory(float* d_A) { <br>    cudaError_t err ;<br>    err = cudaFree(d_A);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaFree failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>        <br>    }<br>    printf(&quot;Deallocated GPU memory\n&quot;);<br>}<br><br>// Mevcut ve toplam GPU memorysini gösteren proc<br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %f GB\n&quot;, free_mem , free_mem / (1024.0*1024.0*1024.0));<br>    printf(&quot;Total GPU memory: %zu bytes, %f GB\n&quot;, total_mem ,total_mem / (1024.0*1024.0*1024.0));<br>}<br><br>int main()<br>{<br>    // CUDA cihaz özelliklerini al<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo(); // Bellek durumunu yazdır<br><br>/*<br>    int* vectorA = nullptr;<br>    int* vectorB = nullptr;<br>    int* vectorC = nullptr;<br>*/<br><br>    float* vectorA = nullptr;<br>    float* vectorB = nullptr;<br>    float* vectorC = nullptr;<br><br>    // İşlenecek veri boyutunu belirle (1 GB veri)<br>    long long total_bytes = 1024LL * 1024 * 1024; <br>    long long num_elements_total = total_bytes / sizeof(float);<br>    printf(&quot;sizeoffloat:%zu\n&quot;,sizeof(float));<br><br>    int blockSize = 1024;  // CUDA block boyutu<br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br>    <br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br>    printf(&quot;Block size: %d\n&quot;, blockSize);<br>    printf(&quot;Number of blocks: %lld\n&quot;, numBlocks_required);<br><br>    // CUDA zaman ölçümü için event oluştur<br>    cudaEvent_t start, stop;<br>    float milliseconds=0.0f;<br>    cudaEventCreate(&amp;start);<br>    cudaEventCreate(&amp;stop);<br>    <br>    // Memory allocation için zamanı ölç<br>    cudaEventRecord(start);<br>    allocateMemory(&amp;vectorA, num_elements_total * sizeof(float));<br>    allocateMemory(&amp;vectorB, num_elements_total * sizeof(float));<br>    allocateMemory(&amp;vectorC,num_elements_total * sizeof(float));<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br><br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for GPU global memory allocations: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörlere ilk değerleri ata <br>    cudaEventRecord(start);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the initialization of the vectors: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörleri topla (kernel çalıştır)<br>    cudaEventRecord(start);<br>    simpleVectorAdd&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, vectorB, vectorC, num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the kernel: %f milliseconds\n&quot;,milliseconds);<br><br>    // Kernel hatalarını kontrol et  <br>    cudaError_t kernelError = cudaGetLastError();<br>    if (kernelError != cudaSuccess) {<br>        fprintf(stderr, &quot;Kernel launch failed: %s\n&quot;, cudaGetErrorString(kernelError));<br>    }<br><br>    displayMemoryInfo();<br><br>    printf(&quot;\n&quot;);<br>    deAllocateMemory(vectorA);<br>    deAllocateMemory(vectorB);<br>    deAllocateMemory(vectorC);<br>  //  free(outputforCpu);<br>    //cudaDeviceReset(); <br>    displayMemoryInfo();<br><br>    return 0;<br>   <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54Dltw4IE6f09M_21AidpQ.png" /><figcaption>GPU üzerinde float değerlerle çarpma işlemi</figcaption></figure><p>Görünürde pek değişiklik olmadı , sadece float değişkenlere ilk değerleri atama işlemi daha uzun sürdü ( 9ms lerden 29 ms seviyelerine geldik)</p><p>Bu işlem için almış olduğumuz ncu rapor sonuçlarına bakalım :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vpGItBwLpP_xSTyp3Doew.png" /><figcaption>GPU üzerinde float değerlerin çarpılmasına ait nsight compute raporu(Summary)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJPC5V9mLTZFR1ak2sJc1g.png" /><figcaption>GPU üzerinde float değerlerin çarpılmasına ait nsight compute raporu(Details)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsQLw3UD0Y-YjIQaWaCheA.png" /><figcaption>GPU üzerinde float değerlerin çarpılmasına ait nsight compute raporu(Details)</figcaption></figure><p>Daha önceki işlemlerle karşılaştırdığımızda , Compute Throughput değeri float işlem yapınca %77.29’a çıktı, Memory Throughput değeri %26’ya indi. (Grafikteki değişime özellikle dikkat edin) Ek olarak rapor artık Very High Utilization olarak son durumu belirtiyor,daha önce görmediğimiz FP64 işlemlerinin de ne kadar yüksek olduğuna dikkatinizi çekiyorum. Sonuç olarak float işlem yapınca GPU’nun kapasitesini kullandık ve uygulamamız artık memory bound değil GPU bound durumda. Problem mi? Değil halen ms seviyesinde tamamlanıyor.</p><p>Şimdi de double olarak deneyelim . int ve float değişkenleri 4 byte yer kaplarken , double 8 byte yer istiyor. Aynı işlemi double olarak yapıyoruz:</p><pre>#include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br>// GPU üzerinde vektörü sıfırdan N&#39;e kadar dolduran kernel proc<br> __global__ void initializeVector(double* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx*1.0;<br>    }<br>}<br><br><br>// GPU üzerinde iki vektörü toplayan kernel proc<br>__global__ void simpleVectorAdd(double* A, double* B, double* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] * B[idx] ;<br>        }<br>}<br><br>// GPU belleği yaratan proc<br>void allocateMemory(double** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}<br><br>// GPU memorysini silen proc<br>void deAllocateMemory(double* d_A) { <br>    cudaError_t err ;<br>    err = cudaFree(d_A);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaFree failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>        <br>    }<br>    printf(&quot;Deallocated GPU memory\n&quot;);<br>}<br><br>// Mevcut ve toplam GPU memorysini gösteren proc<br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %f GB\n&quot;, free_mem , free_mem / (1024.0*1024.0*1024.0));<br>    printf(&quot;Total GPU memory: %zu bytes, %f GB\n&quot;, total_mem ,total_mem / (1024.0*1024.0*1024.0));<br>}<br><br>int main()<br>{<br>    // CUDA cihaz özelliklerini al<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo(); // Bellek durumunu yazdır<br><br>/*<br>    int* vectorA = nullptr;<br>    int* vectorB = nullptr;<br>    int* vectorC = nullptr;<br>*/<br><br>    double* vectorA = nullptr;<br>    double* vectorB = nullptr;<br>    double* vectorC = nullptr;<br><br>    // İşlenecek veri boyutunu belirle (1 GB veri)<br>    long long total_bytes = 1024LL * 1024 * 1024; <br>    long long num_elements_total = total_bytes / sizeof(double);<br>    printf(&quot;sizeoffloat:%zu\n&quot;,sizeof(double));<br><br>    int blockSize = 1024;  // CUDA block boyutu<br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br>    <br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br>    printf(&quot;Block size: %d\n&quot;, blockSize);<br>    printf(&quot;Number of blocks: %lld\n&quot;, numBlocks_required);<br><br>    // CUDA zaman ölçümü için event oluştur<br>    cudaEvent_t start, stop;<br>    float milliseconds=0.0f;<br>    cudaEventCreate(&amp;start);<br>    cudaEventCreate(&amp;stop);<br>    <br>    // Memory allocation için zamanı ölç<br>    cudaEventRecord(start);<br>    allocateMemory(&amp;vectorA, num_elements_total * sizeof(double));<br>    allocateMemory(&amp;vectorB, num_elements_total * sizeof(double));<br>    allocateMemory(&amp;vectorC,num_elements_total * sizeof(double));<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br><br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for GPU global memory allocations: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörlere ilk değerleri ata <br>    cudaEventRecord(start);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the initialization of the vectors: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörleri topla (kernel çalıştır)<br>    cudaEventRecord(start);<br>    simpleVectorAdd&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, vectorB, vectorC, num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the kernel: %f milliseconds\n&quot;,milliseconds);<br><br>    // Kernel hatalarını kontrol et  <br>    cudaError_t kernelError = cudaGetLastError();<br>    if (kernelError != cudaSuccess) {<br>        fprintf(stderr, &quot;Kernel launch failed: %s\n&quot;, cudaGetErrorString(kernelError));<br>    }<br><br>    displayMemoryInfo();<br><br>    printf(&quot;\n&quot;);<br>    deAllocateMemory(vectorA);<br>    deAllocateMemory(vectorB);<br>    deAllocateMemory(vectorC);<br>  //  free(outputforCpu);<br>    //cudaDeviceReset(); <br>    displayMemoryInfo();<br><br>    return 0;<br>   <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIHWjP_HeNnBF2XWYU2tDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oM0cBXQdX7HGLn24M_y4TA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_s3Wbj5NC8IQ5wEWzNcm5w.png" /></figure><p>Double 8 byte olunca 1gb. Memory için 268milyonun yarısı kadar eleman işledik. Yine de ComputeSM %62. Şartların aynı olması için burada da 268M data işleyelim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IKX3kq_VbXdUU7FzllVSg.png" /><figcaption>268milyon double değerin GPU’da çarıpımı</figcaption></figure><p>268M . double değişken ile işlem yaptığımızda kernelın calısması 24 ms sürdü.Float değiken için bu işlem 12 ms sürmüştü.</p><p>Şu ana kadar yapmış olduğumuz işlemlerin daha da karmaşık hale getirelim. Matris çarpımını deneyelim. Matris çarpımı şu ana kadar yapmış olduğumuz işlemler gibi her elemana sadece bir kez ulaşarak değil, aynı eleömanların birden fazla kez işlemlerde kullanılması ile yapılıyor. O yüzden bu örnekle beraber daha önce olmayan L1 cache vb. kullanımını da göreceğiz .</p><pre>#include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br>// Mevcut vektörleri initialize eden kernel<br>__global__ void initializeVector(double* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx * 1.0;<br>    }<br>}<br><br>// Mevcut vektör toplama kernel<br>__global__ void simpleVectorAdd(double* A, double* B, double* C, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>        C[idx] = A[idx] * B[idx];<br>    }<br>}<br><br>// 🚀 Eklenen yeni matris çarpma kernel (NxN double matrix)<br>__global__ void matrixMultiplyKernel(const double* A, const double* B, double* C, int N) {<br>    int row = blockIdx.y * blockDim.y + threadIdx.y;<br>    int col = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (row &lt; N &amp;&amp; col &lt; N) {<br>        double sum = 0;<br>        for (int k = 0; k &lt; N; ++k) {<br>            sum += A[row * N + k] * B[k * N + col];<br>        }<br>        C[row * N + col] = sum;<br>    }<br>}<br><br>// Mevcut bellek yönetim procları<br>void allocateMemory(double** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}<br>void deAllocateMemory(double* d_A) { <br>    cudaError_t err ;<br>    err = cudaFree(d_A);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaFree failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>    }<br>    printf(&quot;Deallocated GPU memory\n&quot;);<br>}<br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %f GB\n&quot;, free_mem , free_mem / (1024.0*1024.0*1024.0));<br>    printf(&quot;Total GPU memory: %zu bytes, %f GB\n&quot;, total_mem ,total_mem / (1024.0*1024.0*1024.0));<br>}<br><br>int main() {<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo();<br><br>    // Vektör boyutu: ~2 GB<br>    long long total_bytes = 1024LL * 1024 * 1024 * 2; <br>    //long long num_elements_total = total_bytes / sizeof(double);<br>    int N = 4096;<br>    long long num_elements_total = (long long)N * N;<br>    printf(&quot;sizeofdouble:%zu\n&quot;, sizeof(double));<br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br><br>  <br><br>    int blockSize = 1024;<br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br><br>    cudaEvent_t start, stop;<br>    float milliseconds=0.0f;<br>    cudaEventCreate(&amp;start);<br>    cudaEventCreate(&amp;stop);<br><br>    // Memory allocation<br>    double *vectorA = nullptr, *vectorB = nullptr, *vectorC = nullptr;<br>    allocateMemory(&amp;vectorA, num_elements_total * sizeof(double));<br>    allocateMemory(&amp;vectorB, num_elements_total * sizeof(double));<br>    allocateMemory(&amp;vectorC, num_elements_total * sizeof(double));<br><br>    // Initialize vectors<br>    cudaEventRecord(start);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;Initialization time: %f ms\n&quot;, milliseconds);<br><br>    // 🚀 Matrix multiplication (NxN with N ~ 16384)<br>    //int N = 4096; //16384;<br>    dim3 threadsPerBlock(16,16);<br>    dim3 blocksPerGrid((N+threadsPerBlock.x-1)/threadsPerBlock.x,<br>                       (N+threadsPerBlock.y-1)/threadsPerBlock.y);<br><br>    cudaEventRecord(start);<br>    matrixMultiplyKernel&lt;&lt;&lt;blocksPerGrid, threadsPerBlock&gt;&gt;&gt;(vectorA, vectorB, vectorC, N);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;Matrix multiplication time: %f ms\n&quot;, milliseconds);<br><br>    deAllocateMemory(vectorA);<br>    deAllocateMemory(vectorB);<br>    deAllocateMemory(vectorC);<br>    displayMemoryInfo();<br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*9hYcfeQSDwderMveziDF4g.png" /></figure><p>16milyon elemanı olan 2 matrisi çarptık. Bu işlem Tesla T4 GPU üzerinde 790ms sürüyor.</p><p>Şimdi bir de GPU’yu değiştirerek çalıştıralım, aynı kodu A100 üzerinde çalıştırırsak 10 kat hızlandığını görüyoruz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*PaICOQTm7kmPmkMbyjz0aA.png" /></figure><p>Peki ne değişti? A100’ün aynı işi T4’ten 10 kat daha hızlı çalıştırabilmesinin nedeni nedir?</p><p>Her ikisinin de ncu raporlarını inceleyelim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQokiQG6JQI78Heiwc2y2w.png" /><figcaption>T4 üzerinde yapılan matris çarpım işleminin ncu raporu</figcaption></figure><p>Matrixcarpımı yapan Kernelın compute throughputu %96.76, memory throughputunun ise %24 olduğunu görüyoruz.</p><p>Bir de A100’e bakalım :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3rhsozKxM8ZkqQwPm-jiw.png" /><figcaption>A100 üzerinde yapılan matris çarpım işleminin ncu raporu</figcaption></figure><p>Önemli gördüğüm değerleri bir tabloda karşılaştırmak amacıyla topladım :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fslhZqBTkI7AyafOq8h7A.png" /><figcaption>Matris carpımı (cuda c) için T4 ve A100 Karşılaştırması</figcaption></figure><p>A100 GPU T4’e göre daha fazla hesaplama kapasitesine sahip bu yüzden T4’tekine göre compute throughputumuz daha az , T4’ün hemen hemen tümünü tüketmiş durumdayız. T4’te GPU Bound durumdayız , böyle olduğu için GPU’nun global memorysini iyi kullanamıyoruz , ama A100’de hesaplama kapasitesi daha fazla oldupu için Memory Bound durumdayız . A100 üzerindeki işlemi optimize etmek için shared memory kullanımı vb. değişiklikler yapmalıyız. T4 üerinde 887milyon cycle ile yaptığımız işi A100 üzerinde 82milyon cycle ile yapabildik.( 10 kat fark var) A100 üzerinde L1 cachei sonuna kadar kullandık , bu noktadan sonra shared memory kullanmak işe yarayabilir. Ama T4 üzerinde zaten GPU Bound durumda oldupumuz için memory tarafında sağlayacğımız bir fayda bulunmuyor.</p><p>Bu örnekle c cuda incelemesini sonlandırıyorum . Buradan sonra daha high level frameworklerin ( Python , cudf) incelemesi ile devam ediyorum .</p><p><strong>cuPy kullanımı:</strong></p><p>Öncelikle pythonda cuPy ile iki matrisi GPU üzerinde çarpan program yazalım.</p><pre>import cupy as cp<br>import time<br><br># Matrix boyutu (NxN)<br>N = 4096<br>num_elements = N * N<br>element_size = cp.dtype(cp.float64).itemsize<br>total_bytes = num_elements * element_size<br><br>print(f&quot;Matrix size: {N}x{N}&quot;)<br>print(f&quot;Total elements: {num_elements}&quot;)<br>print(f&quot;Total bytes: {total_bytes / (1024 ** 3):.2f} GB&quot;)<br><br># Bellek durumu göster<br>free_mem, total_mem = cp.cuda.runtime.memGetInfo()<br>print(f&quot;Free GPU memory: {free_mem / (1024**3):.2f} GB&quot;)<br>print(f&quot;Total GPU memory: {total_mem / (1024**3):.2f} GB&quot;)<br><br># Bellek ayırma ve zaman ölçümü<br>start_time = time.time()<br>A = cp.empty((N, N), dtype=cp.float64)<br>B = cp.empty((N, N), dtype=cp.float64)<br>C = cp.empty((N, N), dtype=cp.float64)<br>cp.cuda.Device().synchronize()<br>alloc_time = time.time() - start_time<br>print(f&quot;Memory allocation time: {alloc_time * 1000:.3f} ms&quot;)<br><br># Matrisleri doldurma<br>start_time = time.time()<br>A = cp.arange(num_elements, dtype=cp.float64).reshape((N, N))<br>B = cp.arange(num_elements, dtype=cp.float64).reshape((N, N))<br>cp.cuda.Device().synchronize()<br>init_time = time.time() - start_time<br>print(f&quot;Initialization time: {init_time * 1000:.3f} ms&quot;)<br><br># Matris çarpımı<br>start_time = time.time()<br>C = cp.dot(A, B)<br>cp.cuda.Device().synchronize()<br>mul_time = time.time() - start_time<br>print(f&quot;Matrix multiplication time: {mul_time * 1000:.3f} ms&quot;)<br><br># GPU sonuçlarını CPU&#39;ya kopyala ve örnek yazdır<br>C_cpu = cp.asnumpy(C)<br>print(f&quot;C[0,0]: {C_cpu[0,0]}&quot;)<br>print(f&quot;C[-1,-1]: {C_cpu[-1,-1]}&quot;)<br><br># Bellek durumu göster<br>free_mem, total_mem = cp.cuda.runtime.memGetInfo()<br>print(f&quot;Free GPU memory after: {free_mem / (1024**3):.2f} GB&quot;)<br>print(f&quot;Total GPU memory: {total_mem / (1024**3):.2f} GB&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*9adcsJkNIaXpKvdJtcT5cA.png" /></figure><p>Aynı kodun c ile yazılmış haline göre Python cupy kodu biraz daha uzun sürdü, bu da c ile Python arasındaki dil farklarından kaynaklanıyor. Python cuPy kullanığımızda c koduna göre çok daha az detayla ilgileniyoruz , kodda görmüş olduğunuz gibi cp.dot(A,B) diyerek işlemi yaptık, bunun dışında memory allocation vb. konularla ilgilenmedik. Eğer daha fazla kontrol istiyorsak c , ama daha hızlı yazmak istiyorsakta Python kullanarak ilerleyebiliriz. Ncu profilleme raporları çok benzer olduğu için cuPy kodlarının ncu incelemelerini atladım .</p><p>Şimdi de data frame işlemlerine bakalım. İlk olarak pandas kullanarak , CPU üzerinde çalışan bir veri sorgulama işlemi yapalım.</p><pre>import pandas as pd<br>import time<br><br># Örnek veri oluşturalım<br>data = {<br>    &#39;id&#39;: range(1000000),  # 10 milyon satır<br>    &#39;value1&#39;: range(1000000),<br>    &#39;value2&#39;: [x % 10 for x in range(1000000)]<br>}<br><br>start = time.time()<br># Pandas DataFrame (CPU üzerinde)<br>df = pd.DataFrame(data)<br>end = time.time()<br>print(f&quot;Dataframe creation time: {end - start:.4f} seconds&quot;)<br><br># Zaman ölçümü başlat<br>start = time.time()<br><br># SELECT * FROM df WHERE value2 = 5<br>filtered = df[df[&#39;value2&#39;] == 5]<br><br># SELECT COUNT(*) FROM filtered<br>count = filtered.shape[0]<br><br># SELECT value2, COUNT(*) FROM df GROUP BY value2<br>grouped = df.groupby(&#39;value2&#39;).size()<br><br># Zaman ölçümü bitir<br>end = time.time()<br><br>print(f&quot;Filtered count: {count}&quot;)<br>print(&quot;Group by result:\n&quot;, grouped)<br>print(f&quot;Execution time: {end - start:.4f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*4T-BnTQlOajjXXlOF2hAGQ.png" /></figure><p>1milyon kayıt için data framei yaratmak 0.2 sn, filtreleme,count ve group by işlemleri 0.02 sn sürüyor.</p><p>Aynı işlemi cudf ( cuda data frame) ile GPU üzerinde yapalım :</p><pre>import cudf<br>import time<br><br># Örnek veri oluşturalım<br>data = {<br>    &#39;id&#39;: range(1000000),  # 1 milyon satır<br>    &#39;value1&#39;: range(1000000),<br>    &#39;value2&#39;: [x % 10 for x in range(1000000)]<br>}<br><br>start = time.time()<br># Pandas benzeri DataFrame ama GPU üzerinde<br>gdf = cudf.DataFrame(data)<br><br>end = time.time()<br>print(f&quot;Dataframe creation time: {end - start:.4f} seconds&quot;)<br><br># Profil için zaman ölçümü başlat<br>start = time.time()<br><br># SELECT * FROM gdf WHERE value2 = 5<br>filtered = gdf[gdf[&#39;value2&#39;] == 5]<br><br># SELECT COUNT(*) FROM filtered<br>count = filtered.shape[0]<br><br># SELECT value2, COUNT(*) FROM gdf GROUP BY value2<br>grouped = gdf.groupby(&#39;value2&#39;).size()<br><br># Profil için zaman ölçümü bitir<br>end = time.time()<br><br>print(f&quot;Filtered count: {count}&quot;)<br>print(&quot;Group by result:\n&quot;, grouped)<br>print(f&quot;Execution time: {end - start:.4f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*ansB9eZRJ7V7XS-ltklvvA.png" /></figure><p>1milyon kayıt için aynı işlemleri GPU üzerinde yaptığımızda data framei yaratmak 0.17 sn, sorgulama işlemleri de 0.04 sn. sürüyor. Hemen hemen aynı sürelerde tamamlanıyorlar.</p><p>Şimdi bu işlemleri kayıt sayısını arttırarak yapalım, 1milyon yerin 10milyon kayıt kullanalım</p><p>CPU’da çalışma sonuçları:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*wXLVIkNTBxUyHU_56Q0Dcg.png" /></figure><p>GPU ile çalışma sonuçları :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*EFDxKjMDLw2PAfZDwzNvJQ.png" /></figure><p>10 milyon kayda cıkınca , CPU’da ki işlem süresi 0.25sn ye olurken GPU 0.05 sn sürüyor. GPU 10 milyon kayıt için daha iyi sonuç verdi.</p><p>100milyon kaydı deneyelim :</p><p>Yine önce CPU üzerinde çalıştırdım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*pKXidOE93gFb4sMGu7Y0Mw.png" /></figure><p>GPU sonuçları :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*D4xnW2lCpgePLcxluQnAOQ.png" /></figure><p>Farklı çalışma sonuçlarını özetledim :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSa7liSzLISMx7gOQ9FXNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oWe4iHFaU5QSSQ3JqihaQ.png" /></figure><p>Tabloda gördüğümüz durum şu : Kayıt sayısı az olduğunda data frame üzerindeki sorgulamaları CPU veya GPU üzerinde yapmak performans olarak hemen hemen aynı . Fakat kayıt sayısı arttıkça , hem dataframein yaratılması hem de sırgulamaların tamamlanması GPU’da çok daha hızlı gerçekleşiyor. 100milyon kayıt için, GPU üzerinde dataframei yaratmak pandas ile CPU’da yaratmaktan 3,5 kat daha hızlı , sorgulamaksa 15 kat hızlı! Şimdi 100milyon kayıt için oluşturduğum ncu raporunu detaylı inceleyelim:</p><p>!ncu — set full — target-processes all -o report1 python cudf1.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47gPWBAhnRr_X4vLzs5meg.png" /></figure><p>Cudf ile çalıştırdığımız ncu profil sonucunda öncelikle şu ana kadar yapmış oldupumuz testlere göre çok daha fazla Kernel yaratıldığını görüyoruz. Daha önce kendi yazdığımız programlarda Kernel isimlerini kendimiz belirlediğimiz için hangi kernelin ne yaptığını çok kolay inceleyebiliyorduk. Fakat bu örneklerde artık cuDF vb. libraryler kullanıpımız için Kernel isimlerini biz veremiyoruz. Ayrıca Python kodumuzun içerisindeki işlemlerle kernelelları da hemen eşlelştiremiyoruz. Yukarıdaki çıktıda dataframei GPU’da yaratan Kernel hangisi , count , group by işlemleri yapan kernellar hangisi bunları da kolaylıkla göremiyoruz. Peki ne yapabiliriz?</p><p>Bu noktadan sonra cuDF Nvidia’nın RAPIDs Acceleration içerisinde open source olarak üretilmiş bir library olması nedeniyle bu Kernel functionlarını githubdaki kodları üzerinden inceledim . ( <a href="https://github.com/rapidsai/cudf">https://github.com/rapidsai/cudf</a>) Tüm kod repositorysinde __global__ ile başlayan function tanımlarını aradım. Sonuçta cuda c ile geliştirilmiş olan functionların GPU’da çalışması için mutlaka __global__tanımlarının olması gerekiyordu. Birkaç aramadan sonra örneğin <a href="https://github.com/rapidsai/cudf/blob/5cb49f7821abe9f93218572d06143d85deb998f7/cpp/include/cudf/detail/utilities/cuda.cuh#L192">cpp/include/cudf/detail/utilities/cuda.cuh</a> içerisinde singel_threaded_kernel functionını buldum :</p><pre>CUDF_KERNEL void single_thread_kernel(F f)</pre><p>Görüldüğü gibi başında __global__ yerine CUDF_KERNEL makrosu yazılmış , bu makroyu da bulduğumda onun da __global__ tanımını yaptığını gördüm.</p><p>Benzer şekilde copy_range_kernel functionını da buldum , aşağıya onunda başlanguc kısmını ekliyorum :</p><pre>CUDF_KERNEL void copy_range_kernel(SourceValueIterator source_value_begin,<br>                                   SourceValidityIterator source_validity_begin,<br>                                   cudf::mutable_column_device_view target,<br>                                   cudf::size_type target_begin,<br>                                   cudf::size_type target_end,<br>                                   cudf::size_type* __restrict__ const null_count)</pre><p>Bu incelemeye devam ederek cuDF vb. daha detayda neler yapıyor vb. anlayadabiliriz. Örneğin ben şunu merak ettim:</p><p>Daha önceki örneklerde , c ile cudaMalloc kullanarak GPU memorysinde veri için alan yaratıyorduk ve yine bir Kernel yazarak veri alanlarını dolduruyorduk. ( 268milyonluk vektörlerin ilk değerlerini set ettiğimiz kod) Peki cuDF bu işi nasıl yapıyor? cuDF kullanmasaydım , başlangıç için bir databaseden vb. veriyi okuduktan sonra , önce cudaMalloc ile GPU’da memoryi ayırır sonra da veri setinden geçen her kaydı parallel bir şekilde GPU memorysine koyardım.</p><p><a href="https://github.com/rapidsai/cudf/blob/branch-24.06/python/cudf/core/dataframe.py">https://github.com/rapidsai/cudf/blob/branch-24.06/python/cudf/core/dataframe.py</a> koduna örnek olarak baktım , dataframe ile ilgili bir çok işlemin GPU karşılığı vb. mevcut , bunun yanında her dataframe için GPU’da memory ayırmak yerine bir memory pool yaratma vb.</p><p>Aslında en temel sorumun yanıtını bulamadım. Hangi cuDF işleminde hangi Kernel kullanılıyor bunu bilelim ki , ncu raporunu analiz ederken , data frame yaratılırken GPU nasıl kullanıldı , count vb. işlemlerde nasıl kullanıldı anlayabilelim . Bunu bulamadım.</p><p>Bunu anlayabilmek için , kodu değiştirerek her aşamanın sonuna bir ekran çıktısı koydum , böylece ncu çalışırken hangi aşamada hangi Kernel functionlarının çalıştığını netleştirmiş olduk :</p><pre>import cudf<br>import time<br><br># Örnek veri oluşturalım<br>data = {<br>    &#39;id&#39;: range(10000000),  # 10 milyon satır<br>    &#39;value1&#39;: range(10000000),<br>    &#39;value2&#39;: [x % 10 for x in range(10000000)]<br>}<br><br>start = time.time()<br># Pandas benzeri DataFrame ama GPU üzerinde<br>gdf = cudf.DataFrame(data)<br><br>end = time.time()<br>print(f&quot;Dataframe creation time: {end - start:.4f} seconds&quot;)<br><br># Profil için zaman ölçümü başlat<br>start = time.time()<br><br># SELECT * FROM gdf WHERE value2 = 5<br>filtered = gdf[gdf[&#39;value2&#39;] == 5]<br><br>end = time.time()<br>print(f&quot;Execution  for filter: {end - start:.4f} seconds&quot;)<br><br># SELECT COUNT(*) FROM filtered<br>start = time.time()<br>count = filtered.shape[0]<br>end = time.time()<br>print(f&quot;Execution  for count: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br># SELECT value2, COUNT(*) FROM gdf GROUP BY value2<br>grouped = gdf.groupby(&#39;value2&#39;).size()<br>end = time.time()<br>print(f&quot;Execution  for groupby: {end - start:.4f} seconds&quot;)<br><br># Profil için zaman ölçümü bitir<br><br>print(f&quot;Filtered count: {count}&quot;)<br>print(&quot;Group by result:\n&quot;, grouped)<br>#print(f&quot;Execution time: {end - start:.4f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAsHqpyOmJB5dFA7B8wwUA.png" /></figure><p>Şimdi ncu çıktısı cok daha anlamlı hale geldi, dataframe için ilk 5 kernel , filter için sonraki 9 kernel çağrılıyor. Count için Kernel çağrısı yok , group by içinde count_set_bits_kernel ile başlayan kernellar çağrılıyor. Bu şekilde ncu raporuna bakarak yazdığımız kod GPU’yu hangi işlem için nasıl kullanıyor anlayabiliriz.</p><p>Bu noktadan sonra şu soruyu sordum diyelimki bu inceleme sonucunda GPU üzerinde örneğin occupancy değerlerinde problem gördük veya işlemlerin bir kısmının GPU bound bir kısmının memory bound olduğunu anladık, ne yapabiliriz? Daha önce cuda ile kendi kodumuzu yazdığımızda ( c vey a Python farketmiyor) blocksize, numberofblocks , shared memory kullanımı vb. müdaheleler yapabiliyorduk , fakat cuDF vb. kütüphaneler tüm bu işlemleri kendi kodlarının içerisinde yapıyorlar ve bizim bunlara müdahele etmemiz kolay değil. Kütüphanelerin source kodlarına girip değişiklik yapmak vb. mümkün ama bunu da yapmak istemeyiz.Sonuç olarak geldiğim nokta analizi yapıp işleyişi anlıyoruz , bu sayede belki datanın okunması vb. bazı kararlar alabiliriz ama GPU üzerindeki ince ayarları değiştiremiyoruz.</p><p>Şimdi de bir star schema yaratıp , joinleme işlemlerinin CPU ve GPU farkına bakalım.</p><p>Önce pandas kullanarak CPU üzerinde basit bir star schema yaratıyorum ve 10milyonluk bir fact tablo ile tüm dimensionları joinliyorum :</p><pre>import pandas as pd<br>import numpy as np<br>import time<br><br># 🌟 Dimension Tables<br>n_customers = 100000<br>n_products = 10000<br>n_times = 365<br>n_branches = 100<br><br>start = time.time()<br>dim_customer = pd.DataFrame({<br>    &#39;customer_id&#39;: np.arange(n_customers),<br>    &#39;customer_name&#39;: [&#39;Customer_&#39; + str(i) for i in range(n_customers)],<br>    &#39;region&#39;: np.random.choice([&#39;East&#39;, &#39;West&#39;, &#39;North&#39;, &#39;South&#39;], n_customers)<br>})<br>end = time.time()<br>print(f&quot;Dimension Customer creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_product = pd.DataFrame({<br>    &#39;product_id&#39;: np.arange(n_products),<br>    &#39;product_name&#39;: [&#39;Product_&#39; + str(i) for i in range(n_products)],<br>    &#39;category&#39;: np.random.choice([&#39;A&#39;, &#39;B&#39;, &#39;C&#39;], n_products)<br>})<br>end= time.time()<br>print(f&quot;Dimension Product creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_time = pd.DataFrame({<br>    &#39;time_id&#39;: np.arange(n_times),<br>    &#39;date&#39;: pd.to_datetime(np.arange(n_times), unit=&#39;D&#39;, origin=&#39;2022-01-01&#39;),<br>    &#39;year&#39;: 2022 + (np.arange(n_times) // 365)<br>})<br>end= time.time()<br>print(f&quot;Dimension Time creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_branches = pd.DataFrame({<br>    &#39;branch_id&#39;: np.arange(n_branches),<br>    &#39;branch_name&#39;: [&#39;Branch_&#39; + str(i) for i in range(n_branches)],<br>    &#39;city&#39;: np.random.choice([&#39;CityA&#39;, &#39;CityB&#39;, &#39;CityC&#39;], n_branches)<br>})<br><br>end= time.time()<br>print(f&quot;Dimension Branches creation time: {end - start:.4f} seconds&quot;)<br><br>n_transactions = 10000000<br><br>start = time.time()<br>fact_transactions = pd.DataFrame({<br>    &#39;transaction_id&#39;: np.arange(n_transactions),<br>    &#39;customer_id&#39;: np.random.randint(0, n_customers, n_transactions),<br>    &#39;product_id&#39;: np.random.randint(0, n_products, n_transactions),<br>    &#39;time_id&#39;: np.random.randint(0, n_times, n_transactions),<br>    &#39;branch_id&#39;: np.random.randint(0, n_branches, n_transactions),<br>    &#39;amount&#39;: np.random.random(n_transactions) * 100,<br>    &#39;quantity&#39;: np.random.randint(1, 10, n_transactions)<br>})<br><br>end= time.time()<br>print(f&quot;Fact Transactions creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>joined = fact_transactions.merge(dim_customer, on=&#39;customer_id&#39;)\<br>    .merge(dim_product, on=&#39;product_id&#39;)\<br>    .merge(dim_time, on=&#39;time_id&#39;)\<br>    .merge(dim_branches, on=&#39;branch_id&#39;)<br><br>end = time.time()   <br>print(f&quot;Join operation time: {end - start:.4f} seconds&quot;)<br><br>print(f&quot;Joined DataFrame has {len(joined)} rows and {len(joined.columns)} columns.&quot;)<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*Owp4U05av8-wsXEovTpgOg.png" /></figure><p>cudf kodu:</p><pre>import cudf<br>import cupy as cp<br>import numpy as np<br>import time<br>import pandas as pd<br><br># 🌟 Dimension Tables<br>n_customers = 100000<br>n_products = 10000<br>n_times = 365<br>n_branches = 100<br><br>start = time.time()<br>dim_customer = cudf.DataFrame({<br>    &#39;customer_id&#39;: cp.arange(n_customers),<br>    &#39;customer_name&#39;: [&#39;Customer_&#39; + str(i) for i in range(n_customers)],<br>    &#39;region&#39;: np.random.choice([&#39;East&#39;, &#39;West&#39;, &#39;North&#39;, &#39;South&#39;], n_customers)<br>})<br>end = time.time()<br>print(f&quot;Dimension Customer creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_product = cudf.DataFrame({<br>    &#39;product_id&#39;: cp.arange(n_products),<br>    &#39;product_name&#39;: [&#39;Product_&#39; + str(i) for i in range(n_products)],<br>    &#39;category&#39;: np.random.choice([&#39;A&#39;, &#39;B&#39;, &#39;C&#39;], n_products)<br>})<br>end= time.time()<br>print(f&quot;Dimension Product creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br><br>n_times = 1000   <br>start_date = pd.Timestamp(&#39;2022-01-01&#39;)<br><br>date_series = cudf.Series(start_date + pd.to_timedelta(cp.arange(n_times).get(), unit=&#39;D&#39;))<br><br>dim_time = cudf.DataFrame({<br>    &#39;time_id&#39;: cp.arange(n_times),<br>    &#39;date&#39;: date_series,<br>    &#39;year&#39;: 2022 + (cp.arange(n_times) // 365)<br>})<br><br><br><br><br>end= time.time()<br>print(f&quot;Dimension Time creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>dim_branches = cudf.DataFrame({<br>    &#39;branch_id&#39;: cp.arange(n_branches),<br>    &#39;branch_name&#39;: [&#39;Branch_&#39; + str(i) for i in range(n_branches)],<br>    &#39;city&#39;: np.random.choice([&#39;CityA&#39;, &#39;CityB&#39;, &#39;CityC&#39;], n_branches)<br>})<br>end= time.time()<br>print(f&quot;Dimension Branches creation time: {end - start:.4f} seconds&quot;)<br><br>n_transactions = 10000000   <br><br>start=  time.time()<br>fact_transactions = cudf.DataFrame({<br>    &#39;transaction_id&#39;: cp.arange(n_transactions),<br>    &#39;customer_id&#39;: cp.random.randint(0, n_customers, n_transactions),<br>    &#39;product_id&#39;: cp.random.randint(0, n_products, n_transactions),<br>    &#39;time_id&#39;: cp.random.randint(0, n_times, n_transactions),<br>    &#39;branch_id&#39;: cp.random.randint(0, n_branches, n_transactions),<br>    &#39;amount&#39;: cp.random.random(n_transactions) * 100,<br>    &#39;quantity&#39;: cp.random.randint(1, 10, n_transactions)<br>})<br>end= time.time()<br>print(f&quot;Fact Transactions creation time: {end - start:.4f} seconds&quot;)<br><br>start = time.time()<br>joined = fact_transactions.merge(dim_customer, on=&#39;customer_id&#39;)\<br>    .merge(dim_product, on=&#39;product_id&#39;)\<br>    .merge(dim_time, on=&#39;time_id&#39;)\<br>    .merge(dim_branches, on=&#39;branch_id&#39;)<br>end = time.time()   <br>print(f&quot;Join operation time: {end - start:.4f} seconds&quot;)<br><br>print(f&quot;Joined DataFrame has {len(joined)} rows and {len(joined.columns)} columns.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*IXrNVkO8hBzVMCpqPpCT0Q.png" /></figure><p>10milyon kayıt için CPU’da 8 sn. süren joinleme işlemi GPU’da 0.3 sn. sürüyor. Kayıt sayısını da arttırdıkça GPU performans olarak CPU’ya göre çok daha iyi :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZTBKfw_V5_fyyMjOpIRbg.png" /></figure><p>Bu yazının ikinci bölümünde GPU’ların hakkını vermek için nasıl daha karmaşık işlemler gerçekleştirebileceğimizi ve performans analizlerini nasıl yapabileceğimizi öğrendik. İlk bölümde basit vektör işlemlerini incelerken, bu bölümde:</p><ul><li><strong>CUDA C kullanarak</strong> integer, float, double veri tipleriyle daha karmaşık işlemler gerçekleştirdik ve matris çarpımını inceledik.</li><li>Farklı GPU mimarileri (T4 vs A100) arasındaki performans farklarını, Compute ve Memory Throughput değerlerini ve kernel performanslarını karşılaştırdık.</li><li><strong>cuPy ve cuDF gibi yüksek seviye Python kütüphaneleri</strong> ile CUDA C’nin karmaşıklığını azaltarak GPU üzerinde veri işleme işlemlerini kolaylaştırdık.</li><li><strong>cuDF ile pandas karşılaştırması</strong> yaparak CPU ve GPU performansını farklı veri büyüklüklerinde karşılaştırdık. Büyük veri setlerinde GPU’nun avantajlarını net bir şekilde gördük.</li><li>ncu raporları üzerinden kernel analizleri yaparak hangi işlemin GPU’yu ne kadar kullandığını, bottleneck noktalarını ve optimizasyon fırsatlarını tespit etmeyi öğrendik.</li></ul><p>Sonuç olarak, GPU kullanımında <strong>veri büyüklüğü ve algoritmanın karmaşıklığı</strong> büyük rol oynuyor. Küçük veri setlerinde CPU ve GPU performansları yakınken, veri boyutu arttıkça GPU’nun avantajı belirginleşiyor. CUDA C ile düşük seviye kontrol sağlarken, cuPy ve cuDF gibi kütüphanelerle daha hızlı ve pratik kodlar yazılabiliyor. Ancak kernel düzeyinde optimizasyon için kaynak kodlarına bakmak ve profil raporlarını detaylı incelemek halen önemli.</p><p>Yazının 3.bölümünde ML algortimaları için cuML’i ve data işleme için distributed GPU memory kulanımını sağlayan DASK’ı inceleyeceğiz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21dd78dcf43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPU’ların Hakkını Veriyor muyuz?]]></title>
            <link>https://medium.com/@utolgaevren/gpular%C4%B1n-hakk%C4%B1n%C4%B1-veriyor-muyuz-f34d216793e3?source=rss-715b2d3a673a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f34d216793e3</guid>
            <dc:creator><![CDATA[Utkan Tolga Evren]]></dc:creator>
            <pubDate>Tue, 27 May 2025 22:18:34 GMT</pubDate>
            <atom:updated>2025-05-28T04:50:48.368Z</atom:updated>
            <content:encoded><![CDATA[<p>GPU’lar yüksek maliyetli ve sınırlı kaynaklar. Acaba GPU’ları verimli ve etkin bir şekilde kullanıyor muyuz? Bu yazıda GPU kullanımının izlenme ve optimizasyon yöntemlerinden bahsediyorum.</p><p>Bu konuyu incelemeye başladığımda şu soruları sordum:</p><p>1. GPU’larda çalıştırılan işlemler ne kadar optimize çalışıyor nasıl anlayabilirim?</p><p>2. GPU’da optimizasyon yapmak ne demek?</p><p>3. GPU’da ne tür işlemleri kullanabiliyoruz? Deep learning , Ml , data transformation vb. hangisi uygun?</p><p>4. C Cuda mı kullanmalıyım , yoksa Pythonda PyCUDA veya CuPy mı?</p><p>5. Python’da GPU kullanarak yazdığım kodun GPU performansını nasıl görebilirim?</p><p>6. GPU , pandas,spark hangisi daha iyi?</p><p>1 ve 2. Maddeleri bu yazıda inceliyorum , diğer maddeleri bir sonraki yazımda inceleyeceğim.</p><p>Önce en basitten başladım, sadece GPU memorysini kullanan bir c programı yazdım:</p><pre>#include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br>__global__ void emptyKernel() {<br>    <br>}<br><br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %zu GB\n&quot;, free_mem , free_mem / (1024*1024*1024));<br>    printf(&quot;Total GPU memory: %zu bytes, %zu GB\n&quot;, total_mem ,total_mem / (1024*1024*1024));<br>}<br><br>int main()<br>{<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo();<br><br>    long long total_bytes = 1024LL * 1024 * 1024; <br>    long long num_elements_total = total_bytes / sizeof(int);<br><br>    int blockSize = 1024; <br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br>    <br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br>    printf(&quot;Block size: %d\n&quot;, blockSize);<br>    printf(&quot;Number of blocks: %lld\n&quot;, numBlocks_required);<br>    <br>    emptyKernel&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;();<br>    <br>    cudaError_t kernelError = cudaGetLastError();<br>    if (kernelError != cudaSuccess) {<br>        fprintf(stderr, &quot;Kernel launch failed: %s\n&quot;, cudaGetErrorString(kernelError));<br>    }<br><br>    displayMemoryInfo();<br>    return 0;<br>   <br>}</pre><p>Bunu çalıştırmak için nvcc ile compile ediyoruz, Google colab üzerinde aşağıdaki gibi yaptım:</p><p>!nvcc -o testGPUsimple testGPUsimple.cu -arch=sm_75</p><p>Bununla testGPUsimple.cu compile ediliyor ve testGPUsimple adında bir executable dosya oluşuyor. Şimdi bunu direk çalıştırabiliriz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*GvwyC0nRY6vB9gUH8NkpYg.png" /></figure><p>Sonuç olarak, sadece GPU bellek bilgilerini yazdıran basit bir test programı elde etmiş olduk. Colab üzerinde bu programı Tesla T4 GPU ile çalıştırdım.Detaylara geçmeden önce bir de bu hiçbir şey yapmayan programın profilini alalım . Bunun için ncu kullanıyoruz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*DkUqp7X-mPofKHZhpfHVnA.png" /></figure><p>Ncu , GPU üzerindeki metrikleri hesaplayarak profile1 isimli dosyaya kaydetti. Bu dosyayı nvidia nsight compute kullanarak açıp tüm profil sonuçlarını görebiliyoruz :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fk2IaRN4FhbgzJVlM6vRCg.png" /></figure><p>Şimdi buradan başlayarak önemli gördüğüm noktaları detaylandıracağım.</p><p>Öncelikle cuda ile GPU üzerinde çalışacak kod yazmak için c kodunun içinde ( cuda için uzantısı .cu) __global__ tanımlaması yapıyoruz. Bu tanımlamanın olduğu proc , GPU üzerinde çalışacak kod demek:</p><pre>__global__ void emptyKernel() {<br>    <br>}</pre><p>emptyKernel içinde yer alan kodlar GPU üzerinde çalıştırılacak kodlar. GPU tamamen paralel işlem yapabilmek amacıyla tasarlanmış olduğu için , birbirine bağımlı olmayan adımlardan oluşan hesaplamaları paralel threadler sayesinde çok hızlı yapabiliyor. Vektörleri toplama buna örnek bir basit matematiksel işlem. ( Örnek olarak bunu aşağıda yapacağız ) GPU’nun ne kadar kullanıldığını görebileceğimiz işletim sistemi araçları sadece genel değişkenleri gösterebiliyor. ( Örneğin Windows task managerda GPU’ların utilizasyon oranları gözüküyor) Ama nvidia nsight compute çok zengin bir değişken içeriğine sahip , çok daha fazla detay bilgi sunuyor. Yukarıdaki hiçbir şey yapmayan kodumuzun profil summary ekranına bakalım , öncelikle emptyKernel’ı burada görüyoruz ( GPU’da çalışan bu kod blokları için kernel terimi de kullanılyor. ) emptyKernel 2.89ms. sürmüş.Hemen alt tarafta “Achieved Occupancy” değerinin %42 olduğu ve %58 lik bir iyileştime yapılabileceği belirtilmiş. ( nsight compute detaylı bir şekilde metriklerin açıklamasını yapıyor) Occupancy önemli bir değişken. Bu değer, kullanılan blok ve thread sayılarının GPU mimarisiyle ne kadar uyumlu olduğunu gösteriyor. Daha iyi blok boyutu seçilerek, daha fazla işi paralel çalıştırabiliyoruz. Ne kadarlık bir paralel işlem yapma kapasitesine sahibiz , aynı anda kaç işlem ( buna thread diye düşünelim) çalıştırabiliriz , biz kaçını çalıştırabiliyoruz bunu gösteriyor. Diyelim ki integerlardan oluşan 2 vektör(dizi) var ve bunları toplamak istiyorum. Bu vektörlerde büyük olsun , büyüklükleri 1GB. olsun. Memoryde1gb büyüklüğünde integerlardan oluşan bir dizi yaratmak istersek bu dizinin eleman sayısı 1GB= 1024*1024 / 4 ( 1 integer 4 byte olduğu için) 268.435.456 olur. İçinde 268milyon sayı olan 2 tane vectorü toplayıp yeni bir vectör elde etmek istiyoruz , formülle ifade edersek aşağıdaki gibi olur:</p><p>C[i] = A[i] +B[i]</p><p>Burada görüldüğü gibi adımlar tamamen birbirinden bağımsız. C[2] değerini hesaplamak için C[1]’e , C[0] ‘a veya başka bir değere ihtiyacımız yok. Bu işlemi Cpu üzerinde seri olarak şöyle yapabilirdik:</p><p>For (int i=0; i&lt;268435456; i++) {</p><p>C[i] = A[i] + B[i];</p><p>}</p><p>For loop ile bu işlem paralel değil arka arkaya çalışıp sonuçlanır. GPU kullandığımızda ise aynı işlemi paralel çalıştırıp çok daha hızlı sonuçlandırabiliyoruz. İlgili değişkenleri belirterek bu toplama işlemini 32, 64 , 128 vb. paralelliklerde çalıştırabiliriz. Ama çok daha iyisini de yapabiliyoruz. Bu işlemi 268435456 paralellikte çalıştırıp çok çabuk bitirebiliyoruz!</p><p>Şimdi bizim hiçbir şey yapmayan kernelımıza bu işlemi ekleyelim:</p><pre>__global__ void simpleVectorAdd(int* A, int* B, int* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] + B[idx] ;<br>        }<br>}</pre><p>Artık GPU’da çalışan bir kodumuz var. Diyelim ki bizim GPU’muz “tek sefer”de 100 işlem yapabiliyor , ama biz sadece 2 paralellik vererek kodumuzu çalıştırıyoruz , bu durumda “theoretical occupancy” değeri 100 , “achieved occupancy” değeri ise %2 oluyor. Nvidia compute profilleme ekranının bize estimated speedup olarak bu durumda göstereceği değer %98. Daha çok paralellik vererek işlemi hızlandırabiliriz. Sonuç olarak bakacağımız ilk yer ne kadar paralell işlem kapasitesi kullandığımız.</p><p>Önemli bir konu olarak “tek sefer” ifadesini açmakta fayda görüyorum. Cpu, GPU vb. senkron çalışan elektronik devrelerden oluşuyor. Yani her ne oluyorsa belirli bir frekansta oluşan “cycle” larda oluyor. GPU, işlemleri paralel olarak aynı anda yürütüyor ve bu işlemler CUDA kernel fonksiyonlarının her çağrısında binlerce küçük işlem dizisi (warp) olarak GPU çekirdeklerine dağıtılıyor.Peki ne kadar paralel işlem istiyoruzu nerede belirliyoruz?</p><p>Java veya c++ ile multithreaded program yazarken, sadece thread sayısını belirtiyorduk. GPU’da biraz daha fazla parametre var 😊</p><pre>emptyKernel&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;();</pre><p>Paralel işlem sayısını block sayısı ve her blockta yer alan paralel işlem sayısı ( thread sayısı) şeklinde belirtiyoruz . İstersek 1 block ve 32 blocksize ile 268milyonluk 2 diziyi toplayabiliriz , veya 2 block 1024 thread ile bu işlemi yapabiliriz. Bunu genel olarak şöyle hesaplamak mümkün:</p><pre>long long total_bytes = 1024LL * 1024 * 1024; <br>long long num_elements_total = total_bytes / sizeof(int);<br>int blockSize = 1024; <br>long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;</pre><p>num_elements_total 268milyon , blocksize için 1024 ( her bir blokta aynı anda çalışacak toplam thread sayısı) seçtiğimizde gerekli blok sayısı yukarıdaki son satırda yer alan formülle hesaplandığında 262144 çıkıyor. 262144 blok ve 1024 thread sayısı ile 268 milyonluk 2 vektörü 268 milyon parallelikte toplayabiliyoruz 😊</p><p>Şimdi bunu deneyip profil sonuçlarına bakalım , kodda bazı eklemeler ve değişiklikler yaptım:</p><pre> #include &quot;cuda_runtime.h&quot;<br>#include &quot;device_launch_parameters.h&quot;<br>#include &lt;cuda.h&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;stdio.h&gt;<br><br>// GPU üzerinde vektörü sıfırdan N&#39;e kadar dolduran kernel proc<br>__global__ void initializeVector(int* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx;<br>    }<br>}<br><br>// GPU üzerinde iki vektörü toplayan kernel proc<br>__global__ void simpleVectorAdd(int* A, int* B, int* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] + B[idx] ;<br>        }<br>}<br><br>// GPU memorysi yaratan proc<br>void allocateMemory(int** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}<br><br>// GPU memorysini silen proc<br>void deAllocateMemory(int* d_A) { <br>    cudaError_t err ;<br>    err = cudaFree(d_A);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaFree failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>        <br>    }<br>    printf(&quot;Deallocated GPU memory\n&quot;);<br>}<br><br>// Mevcut ve toplam GPU memorysini gösteren proc<br>void displayMemoryInfo() {<br>    size_t free_mem, total_mem;<br>    cudaMemGetInfo(&amp;free_mem, &amp;total_mem);<br>    printf(&quot;Free GPU memory: %zu bytes , %f GB\n&quot;, free_mem , free_mem / (1024.0*1024.0*1024.0));<br>    printf(&quot;Total GPU memory: %zu bytes, %f GB\n&quot;, total_mem ,total_mem / (1024.0*1024.0*1024.0));<br>}<br><br>int main()<br>{<br>    // CUDA cihaz özelliklerini al<br>    cudaDeviceProp prop;<br>    cudaGetDeviceProperties(&amp;prop, 0);<br>    printf(&quot;CUDA device name: %s\n&quot;, prop.name);<br>    displayMemoryInfo(); // Bellek durumunu yazdır<br><br>    int* vectorA = nullptr;<br>    int* vectorB = nullptr;<br>    int* vectorC = nullptr;<br><br>    // İşlenecek veri boyutunu belirle (1 GB veri)<br>    long long total_bytes = 1024LL * 1024 * 1024; <br>    long long num_elements_total = total_bytes / sizeof(int);<br><br>    int blockSize = 1024;  // CUDA block boyutu<br>    long long numBlocks_required = (num_elements_total + blockSize - 1) / blockSize;<br>    <br>    printf(&quot;Number of elements: %lld\n&quot;, num_elements_total);<br>    printf(&quot;Block size: %d\n&quot;, blockSize);<br>    printf(&quot;Number of blocks: %lld\n&quot;, numBlocks_required);<br><br>    // CUDA zaman ölçümü için event oluştur<br>    cudaEvent_t start, stop;<br>    float milliseconds=0.0f;<br>    cudaEventCreate(&amp;start);<br>    cudaEventCreate(&amp;stop);<br>    <br>    // Memory allocation için zamanı ölç<br>    cudaEventRecord(start);<br>    allocateMemory(&amp;vectorA, num_elements_total * sizeof(int));<br>    allocateMemory(&amp;vectorB, num_elements_total * sizeof(int));<br>    allocateMemory(&amp;vectorC,num_elements_total * sizeof(int));<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br><br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for GPU global memory allocations: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörlere ilk değerleri ata <br>    cudaEventRecord(start);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>    initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the initialization of the vectors: %f milliseconds\n&quot;,milliseconds);<br><br>    // Vektörleri topla (kernel çalıştır)<br>    cudaEventRecord(start);<br>    simpleVectorAdd&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, vectorB, vectorC, num_elements_total);<br>    cudaEventRecord(stop);<br>    cudaEventSynchronize(stop);<br>    cudaEventElapsedTime(&amp;milliseconds, start, stop);<br>    printf(&quot;gpu Execution time for the kernel: %f milliseconds\n&quot;,milliseconds);<br><br>    // Kernel hatalarını kontrol et  <br>    cudaError_t kernelError = cudaGetLastError();<br>    if (kernelError != cudaSuccess) {<br>        fprintf(stderr, &quot;Kernel launch failed: %s\n&quot;, cudaGetErrorString(kernelError));<br>    }<br><br>    displayMemoryInfo();<br><br>    // GPU sonuçlarını CPU&#39;ya kopyala<br>    int* vectorA_Cpu = (int*) malloc(num_elements_total * sizeof(int));<br>    int* vectorB_Cpu = (int*) malloc(num_elements_total * sizeof(int));<br>    int* outputforCpu = (int*) malloc(num_elements_total * sizeof(int));<br>    cudaMemcpy(vectorA_Cpu, vectorA, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost); <br>    cudaMemcpy(vectorB_Cpu, vectorB, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost);     <br>    cudaMemcpy(outputforCpu, vectorC, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost); <br>    <br>    // İlk 5 ve son 5 sonucu yazdır<br>    printf(&quot;First 10 and last 10 elements of the output vector:\n&quot;);<br>    for (int i = 0; i &lt; 5; i++) {<br>        printf(&quot;%d + %d = %d\n&quot;, vectorA_Cpu[i],vectorB_Cpu[i],outputforCpu[i]);<br>    }<br>    printf(&quot;\n&quot;);<br>    for (int i = num_elements_total-1; i &gt; num_elements_total-6; i--) {<br>        printf(&quot;%d + %d = %d\n&quot;, vectorA_Cpu[i],vectorB_Cpu[i],outputforCpu[i]);<br>    }<br><br>    printf(&quot;\n&quot;);<br>    deAllocateMemory(vectorA);<br>    deAllocateMemory(vectorB);<br>    deAllocateMemory(vectorC);<br>    free(vectorA_Cpu);<br>    free(vectorB_Cpu);<br>    free(outputforCpu);<br>    //cudaDeviceReset(); <br>    displayMemoryInfo();<br><br>    return 0;<br>   <br>}</pre><p>Bu sefer 2 vektorü toplayıp sonucu 3. bir vektore yazıyoruz. Her vektör 1gb büyüklüğünde, integerlardan oluşuyor ve 268milyon eleman içeriyor. GPU’da yapılan 3 işlem var:</p><ol><li>GPU’da memory ayırma işlemi :</li></ol><pre>allocateMemory(&amp;vectorA, num_elements_total * sizeof(int));<br>allocateMemory(&amp;vectorB, num_elements_total * sizeof(int));<br>allocateMemory(&amp;vectorC,num_elements_total * sizeof(int));</pre><pre>// GPU memorysi yaratan proc<br>void allocateMemory(int** d_A,long long size) {<br>    cudaError_t err ;<br>    printf(&quot;Allocating %lld bytes , %lld GB of GPU memory\n&quot;, size,size/1024/1024/1024);<br>    err = cudaMalloc((void**)d_A, size);<br>    if (err != cudaSuccess) {<br>        fprintf(stderr,&quot;cudaMalloc failed for d_A , error message:%s\n&quot;, cudaGetErrorString(err));<br>     }<br>}</pre><p>GPU’da işlem yapabilmek için öncelikle GPU’nun üzerinde bulunan memorye veriyi kopyalamak gerekiyor. Bunun için cudaMalloc kullanıyoruz .</p><p>2. GPU’da vektörlerin içini doldurma işlemi.</p><pre>initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA,num_elements_total);<br>initializeVector&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorB,num_elements_total);</pre><pre>// GPU üzerinde vektörü sıfırdan N&#39;e kadar dolduran kernel proc<br>__global__ void initializeVector(int* data, long long num_elements) {<br>    long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; num_elements) {<br>       data[idx] = idx;<br>    }<br>}</pre><p>vectorA ve vectorB’yi 0’dan N sayısına kadar dolduruyoruz. Dikkat çekici olan, herhangi bir for loop kullanmaya gerek olmaması. Buradaki initializeVector procedurü, GPU tarafından numBlocks_required ve blockSize parametreleri ile belirlenen paralellikte çalıştırılıyor. Biz idx alanı içerisinde hangi blocktaki hangi threadin çalıştırıldığını anlayıp, ona uygun işlemi yapıyoruz. idx &lt; num_elements kontrolü, vektorün sınırları dışında bir işlem yapmamıza engel olmak için bulunuyor.</p><p>3. GPU’da vektörleri toplama işlemi.</p><pre>simpleVectorAdd&lt;&lt;&lt;numBlocks_required, blockSize&gt;&gt;&gt;(vectorA, vectorB, vectorC, num_elements_total);</pre><pre>// GPU üzerinde iki vektörü toplayan kernel proc<br>__global__ void simpleVectorAdd(int* A, int* B, int* C, long long num_elements)<br>{<br>        <br>        long long idx = blockIdx.x * blockDim.x + threadIdx.x;<br>        if (idx &lt; num_elements) {<br>            C[idx] = A[idx] + B[idx] ;<br>        }<br>}</pre><p>Vektörleri doldurduktan sonra toplama işlemini yapıp sonucu yeni bir vektöre yazıyoruz. Burada da aynı şekilde herhangi bir for loop bulunmuyor. Her thread kendi thread numarasına göre A ve B vektörlerinin verisini okuyup toplayıp sonucu C vektörünün aynı indexi içerisine koyuyor.</p><p>Toplama işlemini yaptıktan sonra sonuçları ekrana yazdırmak için bu sefer CPU üzerinde işlem yapıyoruz. Yaptığımız ilk işlem GPU memorysinden CPU memorysine verileri kopyalamak:</p><pre>    // GPU sonuçlarını CPU&#39;ya kopyala<br>    int* vectorA_Cpu = (int*) malloc(num_elements_total * sizeof(int));<br>    int* vectorB_Cpu = (int*) malloc(num_elements_total * sizeof(int));<br>    int* outputforCpu = (int*) malloc(num_elements_total * sizeof(int));<br>    cudaMemcpy(vectorA_Cpu, vectorA, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost); <br>    cudaMemcpy(vectorB_Cpu, vectorB, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost);     <br>    cudaMemcpy(outputforCpu, vectorC, num_elements_total * sizeof(int), cudaMemcpyDeviceToHost);</pre><p>Bundan sonra ilk 5 ve son 5 değerleri ekrana yazdırarak doğru işlemi yapıp yapmadığımızı anlıyoruz :</p><pre>    // İlk 5 ve son 5 sonucu yazdır<br>    printf(&quot;First 10 and last 10 elements of the output vector:\n&quot;);<br>    for (int i = 0; i &lt; 5; i++) {<br>        printf(&quot;%d + %d = %d\n&quot;, vectorA_Cpu[i],vectorB_Cpu[i],outputforCpu[i]);<br>    }<br>    printf(&quot;\n&quot;);<br>    for (int i = num_elements_total-1; i &gt; num_elements_total-6; i--) {<br>        printf(&quot;%d + %d = %d\n&quot;, vectorA_Cpu[i],vectorB_Cpu[i],outputforCpu[i]);<br>    }</pre><p>Programı çalıştırdığımızda gördüğümüz çıktı şöyle oluyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*xXy9cfuaSAj45SHCEq9OxA.png" /></figure><p>14GB memory bulunan Tesla T4 GPU üzerinde , 1024*262144 paralellik değerleri ile , A,B,C vektörlerini GPU memorysinde allocate etmemiz 0.77 ms , bu vektörleri 268milyon elemanla doldurmamız 9.22ms ,bunları toplamamız 12 ms sürüyor.Toplamda 268 milyon elemanı toplamamız 25ms den az sürdü !!! ( GPU’da çalışan işlemlerin olduğu programı time komutu ile çalıştırıp zamanını ölçtüm , ama time sadece CPU zamanını ölçüyor o yüzden user ve sys zamanlarını dikkate almıyorum, ama real olarak gözüken zaman halen tüm zamanı gösteriyor. Orada görüğümüz 2.5 sn. bizi yanıltmasın , programın içerisinde GPU memorysinden CPU memorysine kopyalama işlemleri var onlar bu zamanınn harcanmasının nedeni. Kod içerisinden bu kopyalama işlemlerini çıkartıp time ile tekrar çalıştırdığımda gördüğüm değerler şöyle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*Eq3tGCgXmb7_A0jks3JoAg.png" /></figure><p>Görüldüğü gibi 0.25 ms. )</p><p>Bir karşılaştırma yapmak için aynı işlemin CPU üzerinde yapılan versiyonunu da aşağıya alarak çalıştırdım :</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;time.h&gt;<br><br>int main() {<br>    // Vektör boyutu<br>    const int N = 268435456;<br><br>    // Vektörler için bellek ayırma<br>    int *a = (int*)malloc(N * sizeof(int));<br>    int *b = (int*)malloc(N * sizeof(int));<br>    int *c = (int*)malloc(N * sizeof(int));<br><br> <br>    clock_t start_time = clock();<br><br>    // a ve b vektörlerini doldurma<br>    for (int i = 0; i &lt; N; i++) {<br>        a[i] = i;<br>        b[i] = i;<br>    }<br><br>    for (int i = 0; i &lt; N; i++) {<br>        c[i] = a[i] + b[i];<br>    }<br><br>   <br>    clock_t end_time = clock();<br><br>    double elapsed_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;<br>    printf(&quot;Islem tamamlama suresi: %f saniye\n&quot;, elapsed_time);<br><br>    // Belleği serbest bırakma<br>    free(a);<br>    free(b);<br>    free(c);<br><br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*jrlXVyWoTg-YjNy6y6nrGA.png" /></figure><p>Cpu’da yaptığımız işlem toplamda 3.10 sn. sürüyor.</p><p>Şimdi ncu ile profilleme sonuçlarını inceleyelim:</p><p>!ncu — set full -o profile2 ./testgpusimplevectoradd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WenrHwQYFOU329hbaQaeQ.png" /></figure><p>Herşeyden önce summary (özet) sayfasında her 3 kernelıda görüyoruz. Her birinin ne kadar sürdüğüde duration alanında (toplamda 21,49ms) gözüküyor. ( Profilleme ile programda yaptığımız zaman ölçümleri arasında bazı farklar olabilir , ncu profillemesi kernellar için daha hassas sonuçlar üretiyor)</p><p>İlk örneğimizle bu çıktıyı karşılaştırırsak , burada estimated speedup %14,14 ve 10 olarak her Kernel için çok daha düşük değerlerde, buda demek oluyor ki GPU üzerinde yüksek miktarda paralellik kullanmayı başardık.”Achieved occupancy” değerine bakarsak %89.2 gibi yüksek bir değerde olduğumuzu görüyoruz. Özetle profil raporuna göre programımız GPU’nun gücünü kullandı.</p><p><strong>Memory Bound ? GPU Bound?</strong></p><p>Şimdi details sayfasına girelim ve aşağıdaki çıktıyı inceleyelim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qaOp-X0L46HhHbGYrk8xRw.png" /></figure><p>Bu ekranda şu an için 2 değişkene dikkat ediyoruz. Compute(SM)Throughput ve Memory Throughput değerleri , alttaki grafikte de bu iki değişken gösterilmiş. Bunları yorumlayalım. Compute(SM)Throughput değeri %23,07. Bunun anlamı şu: bizim programımız GPU’nun computing powerının %23,07 sini kullanıyor. Fakat bir önceki ekranda ”Achieved occupancy” değerinin %89 olduğunu , programın paralelliği çok iyi kullandığını söylemiştim, bu ikisi çelişmiyor mu? Bu aslında tamamen yapmış olduğumuz işlemlerin karmaşıklığı ile ilgili. Paralellik konusunu çok iyi çözdük , ek olarak yaptığımız işlem GPU için çok basit , 2 integerı topluyoruz. GPU çok daha fazlasını yapabilecek durumda bu yüzden biz GPU’nun sadece %23,07 sini meşgul edebildik. Yaptığımız işlemi karmaşık hale getirdikçe ( çarpma , floating sayıların çarpımı vb.) bu değerinde arttığını görürüz. Bu durumda uygulamamız GPU bound durumda değil.</p><p>Şimdi Memory(%) değişkenine bakalım.Burada gördüğümüz değer %89,52. Program çıktısına bakarsak GPU’da 14GB . kapasite var, biz 3GB . kullanıyoruz, Memory %89,52 ne demek? Bu değer bizim memorynin ne kadarını kullandığımızı göstermiyor, bu yüzden 14GB’ın 3GB’ını kullanıyoruz gibi bir anlamı yok. Bu değer GPU memory bandwidth perfomansını ölçüyor. Bizim programımız yapmış olduğu (268 milyon eleman için) okuma , yazma işlemleri ile bu bandwidthin %89unu dolduruyor. GPU’nun global memory’e okuma/yazma veri akışı bant genişliğinin %89’u kullanmış durumdayız. GPUnun işlemci birimleri memoryden daha hızlı, GPU’da yaptığımız işlemlerde çok basit matematik işlemler, bu durumda programımız memory bound durumda.</p><p>Peki bu bir problem mi? Şunu unutmayalım 25 ms.de biten bir programdan bahsediyoruz , herhangi bir problem yaşamıyoruz. Özetle memory bounduz ama bir sorun değil.</p><p>Şimdi aynı ekranda biraz daha aşağılara inelim ve compute workload analiz kısmına gelelim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usq2vboz5P3Unab1kcfgEQ.png" /></figure><p>Bu ekran az önce yazdıklarımın ıspatı sayılır. Görüldüğü gibi GPU üzerinde çok basit işlemler yapılıyor o yüzden sadece ALU ve FMA işlemlerinde az bir yüzde var , en belirgin değer LSU ( load store unit) buda GPU memorysinden okuma yazma işlemlerini gösteriyor , sürekli memoryden okuma yazma yapıyoruz.</p><p>Nsight compute arayüzünün en sevdiğim grafiklerinden bir tanesine geçelim , biraz daha alta indiğimizde memory workload analysis chart bulunuyor şimdi buna bakalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KO4OVoO2J1dLhgrzZZy3YQ.png" /></figure><p>Bu grafik, GPU’daki detaylı bellek kullanımını gösteriyor. En sağda yer alan <strong>Device Memory</strong>, GPU üzerindeki global memory (DRAM) anlamına geliyor. Hemen üstünde yer alan <strong>System Memory</strong>, bilgisayarın RAM’ini gösteriyor.</p><p>GPU işlemcisi, global memory ile veri transferi yaparken işleri hızlandırmak için 3 adet cache mekanizması kullanıyor. Bunların ilki, GPU’ya en yakın olan <strong>L1/TEX Cache</strong>.</p><p><strong>L1/TEX cache</strong>’i programla doğrudan yönetmek mümkün değil; yani bir değişkeni L1/TEX cache içinde tanımlayamıyoruz. L1/TEX cache’in bir kısmı <strong>shared memory</strong> olarak ayrılmış durumda ve bu alan programla yönetilebiliyor. Bazı değişkenleri shared memory içerisinde tanımlayarak global memory erişimlerini azaltabiliriz.</p><p>Peki, bizim örnek programımızdaki 268 milyonluk veriyi shared memory’ye koyup programı hızlandırabilir miyiz? Shared memory büyüklüğü sadece KB seviyesinde olduğundan, tüm veriyi oraya koymak mümkün değil. Ama yine de belirli durumlar için shared memory kullanım yöntemleri var (ileride ayrıca örnekle üzerinden geçeceğim).</p><p>Şimdi grafiğin gösterdiği değerlere bakalım:</p><ul><li><strong>L1 cache hit ratio = 0%.</strong> Bu demek oluyor ki, programımız bellekten ulaştığı verilerin hiçbirini L1 cache’ten vermemiş. Daha doğrusu bu alanı zaten biz yönetemiyoruz; cache’e bir verinin girmesi için ona belirli bir düzenle ve sıkça erişim gerekiyor.</li><li>Yaptığımız işlemin C[i] = A[i] + B[i] olduğunu düşünürsek, her thread farklı bir veri üzerinde çalışıyor ve tekrar erişim yok. Bu yüzden L1 cache’ten bir şey kullanmamak normal.</li></ul><p>Aynı şekilde <strong>L2 cache</strong>’i yorumlayalım:</p><ul><li><strong>L2 cache hit ratio %33.</strong> L2 cache, çok erişilen veriyi global memory’den alıp cache’te saklar ve sonraki erişimlerde global memory’e gitmeden buradan daha hızlı sunar.</li><li>L1’de olduğu gibi burada da erişim düzeni tekrarsız; peki neden %0 değil de %33 çıkıyor?</li><li>Programımız ihtiyaç duyduğu veriyi L1 cache’te bulamadı, L2 cache’te de bulamadı. Bu durumda global memory’den okunan veri L2 cache’e yazıldı ve sonrasında oradan okundu.</li><li><strong>Bu yazma işlemleri grafik tarafından “hit” gibi sayılabiliyor (teknik olarak cache hit okuma işlemi için geçerlidir, yazma değil).</strong> Bu yüzden burada %33 görüyoruz.</li></ul><p>Device memory kutusunun sol tarafındaki sarı çizgi, sağdaki 0 ile 100 arasındaki yoğunluğu gösteriyor. %Memory 89,2 çıkıyor demiştik bu sarı renkte o anlama geliyor.</p><p>Device memory ve L2 cache arasında karşılıklı oklar yer alıyor, 2,36GB ve 1,20GB. Bu değerler sırasıyla device memoryden L2 cache içerisine okunan veri miktarı ile l2 cacheten device memorye yazılan veri miktarını gösteriyor. Yaptığımız işlemin C[i]=A[i] + B[i] olduğunu hatırlarsak , 2 okumaya karşılık 1 yazma için mantıklı değerler görüyoruz.</p><p>Benzer şekilde L1/Tex ile L2 arasında yapılan veri tarnsferlerini de görebiliyoruz. Burada şu soruyu sorarak yazının bu bölümünü sonlandırmak istiyorum : L1 le L2 arasında 2,15gb.lık bir veri transferi varken L1 hit ratio neden 0 ?</p><p>Ncu ve nvidia compute kullanarak GPU’ların performansı nasıl analiz edilir konusuna bir giriş yapmış olduk. Bir sonraki yazımda diğer maddeleri inceleyerek devam etmeyi planlıyorum .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f34d216793e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>