<?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 Reza Mahmoudi on Medium]]></title>
        <description><![CDATA[Stories by Reza Mahmoudi on Medium]]></description>
        <link>https://medium.com/@reza_mahmoudi?source=rss-d7c286d9052d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*m7ZAZRTRsTLksjQg</url>
            <title>Stories by Reza Mahmoudi on Medium</title>
            <link>https://medium.com/@reza_mahmoudi?source=rss-d7c286d9052d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:38:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reza_mahmoudi/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[What are the connections and differences between OpenCV and OpenVX]]></title>
            <link>https://medium.com/@reza_mahmoudi/what-are-the-connections-and-differences-between-opencv-and-openvx-a074f32f4a1a?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a074f32f4a1a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machıne]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 21:24:35 GMT</pubDate>
            <atom:updated>2024-03-08T21:24:35.851Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>The connection and difference is: OpenCV is a cross-platform computer vision and machine learning software library released under the Apache2.0 license (open source). OpenVX implements cross-platform accelerated processing. OpenVX can better leverage its advantages in embedded and real-time systems. In some cases, it can achieve better results with the powerful functions of OpenCV. OpenVX and OpenCV do not conflict, they can be said to be complementary.</em></blockquote><h3>OpenCV</h3><p>OpenCV is a cross-platform computer vision and machine learning software library released under the Apache 2.0 license (open source) and can run on Linux, Windows, Android and Mac OS operating systems. It is lightweight and efficient — it consists of a series of C functions and a small number of C++ classes. It also provides interfaces in Python, Ruby, MATLAB and other languages, and implements many common algorithms in image processing and computer vision.</p><p>OpenCV is written in C++ language. It has C++, Python, Java and MATLAB interfaces and supports Windows, Linux, Android and Mac OS. OpenCV is mainly inclined towards real-time vision applications and utilizes MMX and SSE instructions when available. Nowadays also Provide support for C#, Ch, Ruby, GO.</p><p>OpenCV is written in C++ language, and its main interface is also C++ language, but it still retains a large number of C language interfaces. The library also has extensive interfaces to Python, Java and MATLAB/OCTAVE (version 2.5). API interface functions for these languages ​​can be obtained through online documentation. Now also provides support for C#, Ch, and Ruby.</p><h3>OpenVX</h3><p>OpenVX implements cross-platform accelerated processing. OpenVX can better leverage its advantages in embedded and real-time systems. In some cases, it can achieve better results with the powerful functions of OpenCV. OpenVX and OpenCV do not conflict, they can be said to be complementary. OpenVX aims to facilitate different hardware platforms to implement the same interface. Just like a skeleton, it contains some header files that declare many macros, enumerations, variable types, functions, etc. OpenVX realizes the optimization of performance and energy consumption in computer vision processing, especially plays an important role in embedded and real-time application cases, such as face, body and motion tracking, intelligent video surveillance, advanced driver assistance systems (ADAS), objects and scene reconstruction, augmented reality, visual inspection, robotics, etc. OpenVX defines a higher level of execution abstraction and memory model than computing frameworks such as OpenCL™, bringing important meaning to execution innovation and efficient execution on more architectures, while ensuring that this is the same visual acceleration API as ever, completely Enable application portability.</p><h3>Advantages of OpenCV</h3><p>The computer vision market is huge and continues to grow, and there is no standard API in this regard. There are roughly three types of computer vision software today:</p><p>1. Study the code (slow, unstable, independent and incompatible with other libraries)</p><p>2. Highly expensive commercial tools (such as Halcon, MATLAB+Simulink)</p><p>3. Some special solutions that rely on hardware (such as video surveillance, manufacturing control systems, medical equipment) are the current situation, and standard APIs will simplify the development of computer vision programs and solutions. OpenCV is committed to becoming such a standard API.</p><p>OpenCV is committed to real-world real-time applications. The writing of optimized C code has brought considerable improvements to its execution speed, and faster processing speed can be obtained by purchasing Intel’s IPP high-performance multimedia function library (Integrated Performance Primitives) . Figure 1 shows the performance comparison between OpenCV and other current mainstream visual function libraries.</p><h3>Application of OpenVX in computer vision</h3><p>1. Introduction</p><p>OpenVX is an image and vision processing library that is a standard API maintained by the Khronos Group. The purpose of OpenVX is to provide high-performance hardware-accelerated computer vision functions. It provides a standard interface for building and processing image and video streams, making it easier for developers to take advantage of hardware acceleration.</p><p>2. Core concepts of OpenVX</p><p>The core concepts of OpenVX are graphs and graph operators. A graph is composed of nodes and edges, each node represents an algorithm, and the edges represent dependencies between nodes. In addition, OpenVX also defines some graph operators to implement various functions.</p><p>OpenVX for computer vision</p><p>OpenVX™ is an open, royalty-free API standard for cross-platform acceleration of computer vision applications developed by Khronos Group. The Khronos Group is an open industry consortium of more than 150 leading hardware and software companies creating advanced, royalty-free acceleration standards for 3D graphics, augmented and virtual reality, vision and machine learning. Khronos standards include Vulkan®, OpenCL™, SSYCL™, OOpenVX™, NNNEF™, and many others.</p><p>Now add the Raspberry Pi</p><p>Khronos Group and Raspberry Pi are working together on an open source implementation of OpenVX™ 11.3, approved for Raspberry Pi conformance. The open source implementation passes the Vision, Enhanced Vision and Neural Net conformance profiles specified in OpenVX 1.3 on the Raspberry Pi.</p><p>Application developers are always free to use Khronos standards when they are available on the target system. To enable companies to test the consistency of their products, Khronos h.</p><p>OpenVX enables performance and power-optimized computer vision processing in face, body and gesture tracking, intelligent video surveillance, advanced driver assistance systems (ADAS), object and scene reconstruction, augmented reality, visual inspection, robotics and other embedded and Especially important in real-time use cases. Developers can take advantage of this powerful API in their applications and know that the application will be portable on all compliant hardware.</p><p>4. Application of OpenVX in computer vision</p><h3>1. Image filtering</h3><p>Image filtering is a common computer vision processing method that can make images clearer and more natural. It is very simple to implement the image filtering function using OpenVX. You only need to use the vxGaussian3x3 operator:</p><p>vx_image input_image = vxCreateImage(context, width, height, VX_DF_IMAGE_U8);<br>vx_image output_image = vxCreateImage(context, width, height, VX_DF_IMAGE_U8);<br>vxGaussian3x3(context, input_image, output_image);</p><h3>2. Image segmentation</h3><p>Image segmentation is a common computer vision processing method, which can divide an image into several regions to facilitate further processing of the image. It is also very simple to implement the image segmentation function using OpenVX. You only need to use the vxMeanShift operator:</p><p>vx_image input_image = vxCreateImage(context, width, height, VX_DF_IMAGE_U8);<br>vx_image output_image = vxCreateImage(context, width, height, VX_DF_IMAGE_U8);<br>vxMeanShift(context, input_image, spatial_window, range_window, output_image);</p><h3>3. Feature extraction</h3><p>Feature extraction is a common computer vision processing method, which can extract some important features from images to facilitate more advanced computer vision processing. It is also very simple to implement the feature extraction function using OpenVX. You only need to use the vxHarrisCorners operator:</p><p>vx_image input_image = vxCreateImage(context, width, height, VX_DF_IMAGE_U8);<br>vx_array corners = vxCreateArray(context, VX_TYPE_KEYPOINT, max_corners);<br>vxHarrisCorners(context, input_image, strength_thresh, min_distance, sensitivity, gradient_size, block_size, corners);</p><p>5. Summary</p><p>OpenVX provides a standard API that facilitates developers to use hardware acceleration functions to implement computer vision processing. It can implement functions such as image filtering, image segmentation, and feature extraction. Using OpenVX for computer vision processing is very simple, allowing developers to focus more on algorithm development without paying too much attention to the underlying implementation details.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a074f32f4a1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Increasing the frame rate per second (FPS) is an important consideration when it comes to computer…]]></title>
            <link>https://medium.com/@reza_mahmoudi/increasing-the-frame-rate-per-second-fps-is-an-important-consideration-when-it-comes-to-computer-6e8039c1465d?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e8039c1465d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 20:28:44 GMT</pubDate>
            <atom:updated>2024-03-02T20:28:44.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>Techniques to increase FPS in computer vision task</h3><p>Increasing the frame rate per second (FPS) is an important consideration when it comes to computer vision tasks such as object detection. There are several techniques to increase FPS in computer vision tasks.<br>One technique to increase FPS in object detection is to use a faster deep learning model, such as YOLOv7, which is the leading computer vision algorithm for real-time object detection on COCO and can process up to 286 frames per second . However, faster models often come at the cost of lower accuracy, and it’s important to balance speed and accuracy based on the specific use case.<br>Another technique to increase FPS is to use threading to handle I/O-heavy tasks, such as reading frames from a camera sensor, in a separate thread . The cv2.VideoCapture function and the .read() method used to access the webcam/USB camera are blocking operations, and the main thread of the Python script is completely blocked until the frame is read from the camera device and returned to the script. By moving the reading of frames from a webcam or USB device to an entirely different thread, the frames can be read continuously from the I/O thread while the main thread processes the current frame. This can increase FPS by as much as 379% . However, multithreading can also make the program harder to debug, and using the cv2.imshow function can substantially decrease FPS .<br>A third technique to increase FPS is to reduce the size of the input image. This can be achieved by resizing the image before feeding it into the object detection model. However, this can also lead to a decrease in accuracy if the object becomes too small to detect .<br>A fourth technique to increase FPS is to use hardware acceleration, such as a GPU or a TPU, to speed up the computation. This can significantly increase the speed of deep learning models, especially for large datasets or complex models. However, not all servers or cloud platforms support GPUs or TPUs, and they can be expensive to use .<br>A fifth technique to increase FPS is to optimize the code by using efficient algorithms, reducing redundant computations, and minimizing I/O operations. This can be achieved by profiling the code and identifying the bottlenecks, then optimizing the critical sections of the code. However, this requires a deep understanding of the code and the underlying algorithms, and it can be time-consuming.<br>In conclusion, increasing FPS in computer vision tasks such as object detection can be achieved through a variety of techniques, including using faster deep learning models, using threading to handle I/O-heavy tasks, reducing the size of the input image, using hardware acceleration, and optimizing the code. Each technique has its pros and cons, and the best approach depends on the specific use case and requirements.</p><p>#deeplearning #python #computervision #algorithms #hardware #cv #cloud</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e8039c1465d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An efficiency artifact that accelerates machine learning and big data processing]]></title>
            <link>https://medium.com/@reza_mahmoudi/an-efficiency-artifact-that-accelerates-machine-learning-and-big-data-processing-0fc536401e05?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fc536401e05</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 16:47:15 GMT</pubDate>
            <atom:updated>2024-02-27T16:47:15.405Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you often face the problem that tasks cannot be processed quickly enough to fully utilize computing resources? Especially in the fields of scientific computing and data processing, machine learning and big data processing, how to improve parallel computing efficiency has become a pain point for working programmers in the workplace.</p><p>If you don’t know how to solve it, then listen carefully. Today I will share with you a trick on how to use CPU parallel optimization technology to improve work efficiency — OpenMP technology.</p><p>Imagine that you are developing a complex data processing application, but the single-threaded calculation speed is far from keeping up with the demand. Because as the amount of data and computational complexity continue to increase, the computing power of a single processor has reached a bottleneck. At this time, if you try to use a supercomputer (Supercomputer) to run a program based on C/C++, you will find that it is faster than you can imagine.</p><p>Lets come look</p><p>One day, your application needs to sort massive amounts of data. Traditional serial sorting algorithms can take a lot of time, but using the OpenMP parallel sorting algorithm, you can split the data into multiple subsets, sort them in different threads, and then merge them. This parallelization method allows your sorting tasks to be completed in almost the same time, greatly improving processing efficiency.</p><h3>So how to use Openmp?</h3><p>Generally speaking, the key steps for parallelizing data using OpenMP are as follows:</p><p>1. Divide the data into task blocks of appropriate sizes: According to the characteristics of the data and the nature of the tasks, divide the massive data into multiple task blocks of appropriate sizes for parallel processing.</p><p>2. Create a parallel domain: Use the #pragma omp parallel directive to create a parallel domain, in which the code will be executed by multiple threads at the same time.</p><p>3. Assign tasks to threads: Use the #pragma omp for instruction to assign tasks to different threads, and achieve parallel processing of tasks through iteration.</p><p>4. Processing task blocks: In a parallel loop, each thread is responsible for processing one or more task blocks. Ensure there are no data dependencies and conflicts between tasks to achieve true parallelism.</p><p>The following is a sample code that shows how to use OpenMP to parallelize massive data operations. The specific implementation may be adjusted according to the specific situation:</p><p>In this sample code, we use OpenMP to implement parallel processing of data. By creating parallel domains and using parallel loops, data is divided into multiple task blocks and processed in parallel by different threads. Please note that the actual implementation may vary depending on the specific situation, such as the distribution of data, dependencies between tasks, etc. need to be considered.</p><p>Through this case you will find that whether it is large-scale data analysis, image processing, scientific simulation or machine learning. OpenMP can bring you huge benefits. It provides an easy-to-use instruction set that allows you to easily add parallelization capabilities to existing code. Parallel computing can be achieved by simply marking loops, functions, or blocks of code without requiring large-scale system changes.</p><h3>How good is OpenMP? Let’s take a look at what acceleration problems are generally solved.</h3><p>1. Parallel loop acceleration: OpenMP is suitable for scenarios where loops are accelerated in parallel. For example, in the fields of scientific computing and data processing, loop iteration is a common computationally intensive task. By using OpenMP’s parallel loop instructions, loop iteration tasks can be assigned to multiple threads for simultaneous execution, thereby speeding up calculations.</p><p>2. Parallel task acceleration: OpenMP can also be used to achieve task-level parallel acceleration. In some applications, there are dependencies between tasks, but if the dependencies allow, independent tasks can be executed in parallel through OpenMP to improve the overall computing efficiency. This method is often used in fields such as image processing, simulation and optimization.</p><p>3. Data parallel acceleration: OpenMP can also be used to deal with data parallel problems, that is, parallel processing of data sets. For example, in machine learning and big data analysis, for the processing and analysis of large-scale data sets, OpenMP can be used to parallelize algorithms and operations to speed up processing and improve performance.</p><p>To sum up, OpenMP is mainly used to solve parallelization acceleration problems, including loop acceleration, task acceleration and data parallel acceleration. By leveraging multi-threading and parallel computing, you can improve program performance and efficiency, speed up the computing process, and solve complex computing problems faster.</p><p>Now that we all know that Openmp technology can bring us such great benefits, there is no reason not to learn Openmp technology as a working programmer.</p><p>At the end of the article, I have summarized 10 common technical points of Openmp for you . If you learn how to do it, you will be able to get promoted in a day, your work performance will improve by leaps and bounds, and promotion and salary increase will not be a problem. Please collect it carefully</p><p>1. Parallel Region: Use the #pragma omp parallel directive to create a parallel region, in which the code will be executed by multiple threads at the same time.</p><p>2. Parallel loop (Parallel for): Use the #pragma omp for instruction to divide a loop into multiple tasks and execute them in parallel by different threads.</p><p>3. Number of Threads: Use the omp_set_num_threads function or the OMP_NUM_THREADS environment variable to set the number of threads in the parallel region.</p><p>4. Private Variables: By using the private clause in the parallel region, variables can be declared as private variables, and each thread has its own private copy.</p><p>5. Shared Variables: Use the shared clause to declare variables as shared variables so that multiple threads can access and modify the value of the same variable.</p><p>6. Thread Synchronization: OpenMP provides a variety of ways to achieve synchronization between threads, such as using the #pragma omp barrier directive for barrier synchronization.</p><p>7. Task Parallelism: OpenMP supports the task parallel programming model. By using the #pragma omp task directive to create independent tasks, more fine-grained parallelization can be achieved in the parallel region.</p><p>8. Critical Section: Use the #pragma omp critical directive to create a critical section to ensure that only one thread can execute the code in the critical section at the same time to protect access to shared resources.</p><p>9. Data Sharing Scope: Control the data sharing scope of variables by using the default clause and private and shared clauses in the parallel area.</p><p>10. Environment Settings: OpenMP provides some environment variables and functions to control the behavior of parallel execution, such as the OMP_SCHEDULE environment variable and the omp_get_wtime function.</p><p>In fact, since OpenMP has a wider range of functions and usages, involving more instructions, options and concepts, due to space limitations, only some common OpenMP technical knowledge points are listed here.</p><p>In today’s digital economy era, as the amount of data and computing requirements continue to increase, mastering OpenMP technology has become a crucial capability. Parallel computing has become a core means to solve complex problems in many fields, such as scientific computing, data analysis, machine learning, etc. In this era of information explosion, being able to make full use of parallel computing capabilities can not only greatly improve computing efficiency, but also stand out in the fiercely competitive market.</p><p>At the same time, with the widespread application of multi-core processors, graphics processing units (GPUs) and distributed computing, proficiency in OpenMP technology has become a necessary skill for programmers. Being able to write efficient parallel code and fully utilize the computing potential of the hardware can not only shorten the execution time of the task, but also improve the throughput and responsiveness of the system. This requirement for parallel computing capabilities has become a standard in contemporary technology, and mastering OpenMP technology can easily meet the challenges of parallel computing and achieve more efficient and faster computing tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fc536401e05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement model conversion of AI inference engine?]]></title>
            <link>https://medium.com/@reza_mahmoudi/how-to-implement-model-conversion-of-ai-inference-engine-f21509727d11?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21509727d11</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 06:36:54 GMT</pubDate>
            <atom:updated>2023-12-20T08:41:15.124Z</atom:updated>
            <content:encoded><![CDATA[<p>Many AI frameworks such as PyTorch, Tensorflow, MindSpore, PaddlePaddle, and Oneflow will have training and online reasoning. However, for devices on the device side and edge side, the network model trained by the AI ​​framework needs to be pushed to the AI ​​inference engine for knowledge. Before pushing to the AI ​​inference engine, the push engine will provide a model conversion module Converter.</p><p>I am very curious about how this Converter is implemented. MNN, and tensorRT all provide offline conversion modules. Are there any specific differences?</p><h3>1 Introduction</h3><p>The entire deep learning probably includes feature production, label splicing, training sample generation, model training, and model deployment. As shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*WxaqnVvx7Owvg9gm" /></figure><p>Model deployment is an important part of model application in business. The performance, scalability and timeliness of the inference engine architecture directly restrict the algorithm iteration and development.</p><h3>2. Technology selection</h3><p>First, we sort out the algorithm requirements for online reasoning , and then discuss how to choose.</p><h3>2.1 Algorithm requirements</h3><ul><li>compatibility</li></ul><p>The choice of inference engine architecture will be limited by the model training framework. In order to ensure functional consistency and seamless connection, it needs to be consistent with the offline training engine. Currently tensorflow and pytorch basically occupy more than 80% of the market.</p><ul><li>high performance</li></ul><p>Performance is closely related to resource cost, which is also a factor that must be considered in engineering architecture.</p><ul><li>Scalability</li></ul><p>Algorithm capabilities: equipped with general mechanism expansion operators to improve model expression capabilities</p><p>Processing capabilities: In addition to the inference function, there are generally some other business logics , such as user-side features that require tile expansion or image crop for common transmission. How to expand also has a great impact on business iteration.</p><p>backend extension: the ability to support other inference engines</p><h3>2.2 Comparison of inference engines</h3><h3>Algorithm requirement satisfaction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*8tNi2yAVGtbqJ_qK5DHZpw.png" /></figure><h3>Frame selection</h3><p>Considering the elimination of libtorch from a performance perspective , the main reasons are as follows:</p><ol><li>Libtorch provides runtime through trace script. It lacks pass optimizations such as tf constant folding and CSE, and the performance will be compromised. According to previous tests, the performance is about 30% to 40% of tf.</li></ol><p>Torch serving will face a very difficult problem in the CTR field. When pytorch trains the model, some feature engineering will be implemented outside the model, such as the common bert model tokenizer and padding processing. If it goes online, the online reasoning module needs to migrate this function. In other words, torch serving must have the function of a front-end feature processing module. This is also one of the biggest problems faced by pytorch model deployment. tfsolves this problem through operator combination .</p><p>Considering compatibility, onnxruntime and openvino are eliminated for the following reasons</p><ol><li>Algorithms rarely use these two frameworks for training, and there may be incompatible operators. Moreover, in the CTR field, feature sources are diverse and feature processing methods are also flourishing. Model conversion can encounter various problems. Of course, these two frameworks can be used as supplements.</li></ol><p>These two frameworks actually have their own merits.</p><p>As a common deep learning model expression for business, onnx is basically supported by pytorch model operators, and onnxruntime can be used as the inference engine of pytorch model.</p><p>Openvino is the deep learning inference engine mainly promoted by Intel. It has rich functions and outstanding performance, and is unique in the field of vision.</p><p>From the perspective of versatility, tensorRT is mainly used for GPU scenario elimination.</p><p>So in the end only tensorflow is left.One thing to note here is that different fields and different usage scenarios have certain particularities. It can only be said that the elimination is not suitable at the moment. Different scenarios require different choices. Subsequent chapters will focus on GPU inference performance optimization .3. tensorflow architectureBased on the data flow diagram , a new programming model is proposed. This idea has deeply influenced online architecture design . Graph engines are widely used in Internet companies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*hYRZI2qV1QB9z5lo" /></figure><p>The framework uniformly abstracts heterogeneous devices, uses tensor as a common data type, and operators as the smallest functional unit. It constructs a directed acyclic graph through flexible organization , and the runtime design implements local and remote non-aware use, which is distributed This laid a solid foundation for style training and serving.</p><p>Model format</p><p>Including checkpoint, fronten_graph and saved_model. Currently, saved_model is mainly used without much introduction.</p><pre>def save_model(export_path, sess, inputs, outputs):<br>  if os.path.exists(export_path):<br>    logging.info(&quot;begin to remove the export path {}&quot;.format(export_path))<br>    shutil.rmtree(export_path)<br>  builder = tf.python.saved_model.builder.SavedModelBuilder(export_path)<br>  signature = predict_signature_def(inputs=inputs,<br>                                outputs=outputs)<br>  init_ops = None<br>  builder.add_meta_graph_and_variables(sess=sess,<br>                                   tags=[tag_constants.SERVING],<br>                                   signature_def_map={&#39;serving_default&#39;: signature},<br>                                   legacy_init_op=init_ops)<br>  builder.save(as_text=True)</pre><h3>3.1 tensorflow serving</h3><p>tfs is an engineering-level product with advanced code quality and architectural design concepts, and is worth learning. It makes a servable abstraction for unified resources and provides functions such as resource hot loading, resource expansion, and version management. It is the first choice for tensorflow online reasoning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*xXNtB_mdhHfWy8lv" /></figure><p>From the actual implementation, the following aspects need to be considered:</p><ol><li>If deployed in a microservice cloud-native manner, grpc service gateway, load balancing , circuit breaker and current limiting capabilities are insufficient.</li><li>The RPC proto protocol still has room for optimization, improves business expression capabilities, and supports common transmission of user characteristics to save network costs.</li><li>Lack of pre-processing module, business scalability needs to be enhanced.</li><li>Code maintainability.</li><li>If used for local models, the proto interface will affect performance.</li></ol><p>Therefore, based on the tensorflow library, the technical route of encapsulating model hot loading, version management and RPC services is more in line with business development and function iteration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21509727d11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The difference between NCNN and TensorRT]]></title>
            <link>https://medium.com/@reza_mahmoudi/the-difference-between-ncnn-and-tensorrt-9e869390fe00?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e869390fe00</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 16:44:53 GMT</pubDate>
            <atom:updated>2023-11-29T16:44:53.901Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep learning inference frameworks are often used to infer models deployed on embedded devices. Generally, we use Python on the GPU to train models on different deep learning frameworks (Pytorch, tensorfow, mxnet, etc.), and then convert the trained model into The format supported by the reasoning framework is used, and C++ is used to call the model to accelerate reasoning.</p><p>Let’s briefly summarize the two deep learning inference frameworks NCNN and TensorRT that I have come into contact with since working. NCNN is an inference framework launched by Tencent for mobile deployment. It has no third-party dependencies. The CPU computing speed on the mobile phone is better than the open source framework. Of course it can For reasoning on the PC side, TensorRT is an accelerated reasoning framework launched by NVIDIA for NVIDIA graphics cards. It supports a variety of frameworks and operators.</p><p>The differences are as follows:</p><p>1. NCNN is deployed and optimized for CPU performance and has low memory usage. It provides INT8 quantification support in the author’s latest update GitHub. The network structure and trained model built by the open source framework are converted into .param and .bin formats through conversion tools. The two files are the network and weight files required for NCNN inference. One thing to note here is that when calling the model with C++, you need to use ncnn::Extractor to specify the input and output nodes of the network. If they do not correspond, an error will be reported. This is not very flexible. .</p><p>2.TensorRT optimizes and accelerates model inference for GPU and CPU, supports INT8 quantization and FP16 quantization, TensorRT supports .engine format, there are currently two conversion methods, the first is to first convert the model trained by the open source framework to onnx, and then convert The model in onnx format is converted into .engine; the second method is to directly use tensorrtx (open source) to directly convert the trained model into .engine. TensorRT reconstructs the network during forward reasoning and optimizes and merges some operations. Essentially, it is Nvidia’s optimization of its own GPU characteristics.</p><p>If it is deployed on the mobile side, it is recommended to use the ncnn inference framework. If it is deployed on the edge side such as TX2, Xavier and other devices, it is recommended to use TensorRT. The result of my recent self-test is that the inference performance increased by 40% after switching to TensorRT. Interested friends can compare Try it, welcome to share the deployment process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e869390fe00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Ways to Disrupt Computer Vision Models in Production]]></title>
            <link>https://medium.com/@reza_mahmoudi/4-ways-to-disrupt-computer-vision-models-in-production-b25ec44be3e3?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b25ec44be3e3</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 22:34:42 GMT</pubDate>
            <atom:updated>2023-11-28T22:35:30.441Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction</p><p>This article is not about the quality of the model. It doesn’t even touch on scaling, load balancing and other DevOps. It’s about a more common but sometimes missed thing: dealing with unpredictable user input.</p><p>Data scientists almost always have a controlled data environment when training models. This means working with already prepared data sets, or having the time and resources to collect, merge, clean, and examine the data manually. By doing this accurately, you can improve the quality of models trained on this data.</p><p>Assume the model is good enough to be deployed into production. In the best case, you still have control over the environment (classic server-side deployment). But even then, users upload images from a variety of devices and sources. In the case of edge deployments, there’s an additional layer of complexity: no control over the environment.</p><p>In both cases, the model should respond immediately, leaving developers no time to manually inspect the data. Therefore, it is crucial to:</p><p>· Always have data ready</p><p>· Perform preprocessing as close to training time as possible</p><p>Otherwise, the quality of the actual production model may be much lower than expected. This happens because people introduce bias into the data that the model did not anticipate.</p><p><strong>real case scenario</strong></p><p>In the following content, 4 problems encountered by a company when developing computer vision models will be introduced. Before passing it to an algorithm (mainly a neural network), the following parts are all related to image processing:</p><p>· Orientation stored in EXIF</p><p>· Non-standard color profiles</p><p>· Differences in image libraries</p><p>· Adjust the algorithm</p><p>For each project, a case study and a piece of code are provided to solve the problem in production.</p><p><strong>Orientation stored in EXIF</strong></p><p>Today, people take pictures with mobile cameras (about 91% and this number is growing).</p><p>Typically, mobile devices store images in a predetermined, fixed orientation, regardless of the actual position of the camera when the photo was taken. The angle of rotation required to restore the initial orientation is stored in EXIF ​​as meta-information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YtjVuiCfQdNTbP_V.jpg" /></figure><p>Viewing such images on mobile devices or modern desktop software may be fine as they can handle this EXIF ​​information. But when loading images programmatically, many libraries read the raw pixel data and ignore the meta-information. This results in wrong image orientation. In the example below, I use PIL, one of the most popular Python libraries for image processing.</p><p>input_image = “data/cup.jpg”</p><p>image = PIL. Image. open(input_image)</p><p>np_image_initial = np．array(image)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PIsctNxd0zONrE_J.jpg" /></figure><p>Sending such an image to a neural network may produce completely random results. To solve this problem, you also need to read the EXIF ​​information and rotate/mirror the image accordingly.</p><p>#getimageEXIF</p><p>image_exif = image．getexif()</p><p># retrieve orientation byte</p><p>orientation = image_exif．get(0x0112)</p><p>print(orientation)</p><p>#6</p><p># get the corresponding transformation</p><p>method = {</p><p>2: PIL. Image. FLIP＿LEFT_RIGHT．</p><p>3: PIL. Image. ROTATE＿180，</p><p>4: PIL. Image. FLIP_TOP_BOTTOM，</p><p>5: PIL. Image. TRANSPOSE,</p><p>6: PIL. Image. ROTATE＿270，</p><p>7: PIL. Image. TRANSVERSE,</p><p>8: PIL. Image. ROTATE＿90，</p><p>}. get(orientation)</p><p>if method is not None：</p><p>#replace original orientation</p><p>image_exif［0x0112］＝1</p><p># apply transformation</p><p>image = image. transpose(method)</p><p>np_image_correct = np. array(image)</p><p>PIL allows reading EXIF ​​meta-information and parsing it. It knows where to look for direction. The byte storing the necessary information is 0x0112, and the documentation explains how to handle each value, and how to process the image to restore the initial orientation.</p><p>Cup image read and correctly rotated using EXIF ​​code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ePqZqvDq_ZGMQAzC.jpg" /></figure><p>This issue seems to have been resolved, right? Well, not yet.</p><p>Let’s try another photo. This time, I’ll use the modern HEIF image format instead of the old JPEG (note that a special PIL plugin is required). By default, iPhone shoots HDR pictures in this format.</p><p>Shown is an image of a girl standing in a doorway and its metadata</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D347AJLcG4LDmt8Z.jpg" /></figure><p>Everything looks the same. Let’s try to read it from code in a naive way without looking at EXIF.</p><p>input_image = “data／person.heic”</p><p>image = PIL. Image. open(input_image)</p><p>np_image_initial = np．array(image)</p><p>image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qmJJ1T0THLsM04bT.jpg" /></figure><p>The original image is oriented correctly! But EXIF ​​recommends rotating it 90 degrees counterclockwise! So the bearing recovery code will fail.</p><p>This is a known issue where for some unclear reason the iPhone stores the raw pixels correctly when shooting in HEIC, but still maintains the sensor orientation in EXIF ​​when taking pictures in this format.</p><p>Therefore, when images are captured in HEIC format on iPhone, the algorithm should be corrected and rotation omitted.</p><p>#getimageEXIF</p><p>image_exif = image．getexif()</p><p># get image format</p><p>image_format = image．format</p><p># retrieve orientation byte</p><p>orientation = image_exif．get(0x0112)</p><p>print(orientation)</p><p>#6</p><p>print(image_format)</p><p>#HEIF</p><p># get the corresponding transformation</p><p>method = {</p><p>2: PIL. Image. FLIP＿LEFT_RIGHT．</p><p>3: PIL. Image. ROTATE＿180，</p><p>4: PIL. Image. FLIP_TOP_BOTTOM，</p><p>5: PIL. Image. TRANSPOSE,</p><p>6: PIL. Image. ROTATE＿270，</p><p>7: PIL. Image. TRANSVERSE,</p><p>8: PIL. Image. ROTATE＿90，</p><p>}. get(orientation)</p><p>if method is not None：</p><p>#replace original orientation</p><p>image_exif［0x0112］＝1</p><p># apply transformation if not HEIF</p><p>if image_format! ＝”HEIF”：</p><p>image = image．transpmemoryviewe(method)</p><p>np_image_correct = np. array(image)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i1NNZE7j6Ws8vHc0.jpg" /></figure><p>Of course, there may be more issues with image orientation from other devices, and this code may not be exhaustive. But it clearly demonstrates how cautious one should be with user input, and how unpredictable user input can be even without malicious intent.</p><p><strong>Non-standard color profiles</strong></p><p>Metainformation hides another challenge. Images may be captured and stored in different color spaces and color profiles.</p><p>With color spaces, it’s more or less clear. It defines the channels used to store image color information for each pixel. The two most common color spaces are RGB (red-green-blue) and CMYK (cyan-magenta-yellow-black). One can hardly mistake images in CMYK because they have different numbers of channels: 3 for RGB.</p><p>So sending it to the network will break immediately due to the wrong number of input channels. So this conversion from CMYK to RGB is rarely forgotten.</p><p>Color profiles are much more complex. This is a characteristic of an input (camera) or output (display) device. It describes a device-specific way of recording or displaying colors.</p><p>There are many different profiles for the RGB color space: sRGB, Adobe RGB, Display P3, etc. Each profile defines its own way of mapping raw RGB values ​​to true colors as perceived by the human eye.</p><p>This leads to the fact that the same raw RGB value can mean different colors in different pictures. To solve this problem, you need to carefully convert the color profile of all images to a selected standard.</p><p>Typically, it is an sRGB profile because for historical reasons it is the default color profile for all websites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k_DX_VM_3ZHYxgtL.jpg" /></figure><p>Photos taken on an iPhone usually have a profile that displays P3 colors. Let’s read the image from the code and see what it looks like with and without color profile conversion.</p><p>input_image = “data／city.heic”</p><p>image_initial = PIL. Image. open(input_image)</p><p># open default ICC profile which is sRGB</p><p>working_icc_profile = PIL. ImageCms. getOpenProfile(</p><p>“data/SRGB.icc”</p><p>)</p><p># read ICC profile from the image</p><p>image_icc_profile = PIL. ImageCms. getOpenProfile(</p><p>io. BytesIO (image_initial.info [“icc_profile”])</p><p>)</p><p>#convert an image to default ICC profile</p><p>image_converted = PIL. ImageCms. profileToProfile(</p><p>im=image_initial，</p><p>inputProfile=image_icc_profile，</p><p>outputProfile=working_icc_profile,</p><p>renderingIntent=PIL．ImageCms. INTENT_PERCEPTUAL,</p><p>outputMode=”RGB”</p><p>)</p><p>image_initial_np = np．array(image_initial)</p><p>image_converted_np = np．array(image_converted)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xk-p8NZln3jFRyls.jpg" /></figure><p>It can be seen that the image read through conversion is more vivid and closer to the original image. Depending on the picture and color configuration, this difference may be larger or smaller.</p><p>The colors (i.e. pixel values) sent to the neural network can affect the final quality and ruin the predictions. Therefore, working with them appropriately is crucial.</p><p><strong>Differences in image gallery</strong></p><p>It is very important to read the image correctly. But at the same time, we should do it as quickly as possible. Because in the era of cloud computing, time is money. Additionally, customers don’t want to wait too long.</p><p>The ultimate solution here is to switch to C/C++. Sometimes, in a production reasoning context, it might make perfect sense. But if you want to stay in the Python ecosystem, there are many options. Each image library has its own capabilities and speed.</p><p>Until now, I have only used the PIL module. For comparison, I chose two other popular libraries: OpenCV and Scikit Image.</p><p>Let’s see how fast each library reads JPEG images of different sizes.</p><p>def read_cv2(file):</p><p>image_cv2 = cv2．cvtColor(</p><p>cv2．imread(</p><p>file,</p><p>cv2．IMREAD_UNCHANGED</p><p>),</p><p>cv2．COLOR_BGR2RGB</p><p>)</p><p>return image＿cv2</p><p>def read＿pil(file)：</p><p>image_pil = PIL．Image. open(file)</p><p>＿＝np. array(image_pil)</p><p>return image＿pil</p><p>def read_skimage(file):</p><p>image_skimage = skimage. io. imread(file)</p><p>return image_skimage</p><p>num_repeats = 10</p><p># read 37 JPEG images of different sizes and measure time</p><p>times_read_cv2 = measure_read_times(read_cv2, num_repeats)</p><p>times_read_pil = measure_read_times(read_pil, num_repeats)</p><p>times_read_skimage = measure_read_times(read_skimage, num_repeats)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TbeMf7hTRJQpYvl6.jpg" /></figure><p>For small images, there is almost no difference. But for large ones, OpenCV is about 1.5 times faster than PIL and Scikit images. Depending on the image content and format (JPEG, PNG, etc.), this difference may vary from 1.4x to 2.0x. But overall, OpenCV is much faster.</p><p>There are other reliable benchmarks on the web that give roughly the same numbers. For image writing, the difference is probably even more significant: OpenCV is 4 to 10 times faster.</p><p>Another very common operation is resizing. People almost always resize images before sending them to a neural network. This is where OpenCV really shines.</p><p>times_resize_cv2 = measure_time(</p><p>f=lambda: cv2．resize(image_cv2, (1000, 1000), interpolation=cv2.INTER_LINEAR),</p><p>num=20，</p><p>)</p><p>times_resize_pil = measure_time(</p><p>f＝lambda：image_pil. resize((1000, 1000), resample=PIL.Image.LINEAR),</p><p>num=20，</p><p>)</p><p>times_resize_skimage = measure_time(</p><p>f＝lambda：skimage. transform. resize(image＿skimage, (1000, 1000)),</p><p>num=20，</p><p>)</p><p>print(f”cv2: {np.mean(times_resize_cv2):.3f}s”)</p><p>print(f”pil: {np.mean(times_resize_pil):.3f}s”)</p><p>print(f”skimage: {np.mean(times_resize_skimage):.3f}s”)</p><p>#cv2: 0.006s</p><p>#pil: 0.135s</p><p>#skimage: 4.531s</p><p>Here I took a 7360x4100 image and resized it to 1000x1000. OpenCV is 22 times faster than PIL and 755 times faster than Scikit Image!</p><p>Choosing the right library can save a lot of time. Note that the same resize algorithm may produce different results in different implementations:</p><p>image_cv2_resized = cv2．resize(</p><p>image_cv2，</p><p>(1000, 1000),</p><p>interpolation=cv2．INTER＿LINEAR</p><p>)</p><p>image＿pil＿resized = image＿pil．resize(</p><p>(1000, 1000),</p><p>resample=PIL. Image. LINEAR</p><p>)</p><p>print(</p><p>“Original images are the same:”,</p><p>(image_cv2 == np. array (image_pil)). all()</p><p>)</p><p>print(</p><p>“Resized images are the same:”,</p><p>(image_cv2_resized == np. array (image_pil_resized))．all()</p><p>)</p><p>mae = np. abs(image_cv2_resized.astype(int) -</p><p>np．array(image_pil_resized, dtype=int))．mean()</p><p>print(</p><p>“Mean Absolute Difference between resized images:”,</p><p>f”{mae：.2f}”</p><p>)</p><p># Original images are the same: True</p><p># Resized images are the same: False</p><p># Mean Absolute Difference between resized images: 5.37</p><p>Here one can notice that I am using linear interpolation for downsampling for both OpenCV and PIL. The original image is the same. But the results are different. The difference is significant: an average of 5 out of 255 pixels of each pixel color are different.</p><p>Therefore, if different libraries are used for resizing during training and inference, it may affect the quality of the model. So we should pay close attention to it.</p><p><strong>Adjust the algorithm</strong></p><p>In addition to speed differences between different libraries, even within a library there are different resizing algorithms. Which one should we choose? At least, it depends on whether you want to reduce the image size (downsampling) or increase the image size (upsampling).</p><p>There are many algorithms for resizing images. They produce different image quality and speed. I only look at these 5 that are good enough, fast enough, and supported in mainstream libraries.</p><p>The results provided below are also consistent with some guidelines and examples.</p><p>image = cv2．cvtColor(</p><p>cv2．imread(</p><p>input_image，</p><p>cv2．IMREAD_UNCHANGED</p><p>),</p><p>cv2．COLOR_BGR2RGB</p><p>)</p><p>#define list of algorithms</p><p>algos = {</p><p>“AREA”: cv2. INTER_AREA，</p><p>“NEAREST”: cv2. INTER_NEAREST，</p><p>“LINEAR”: cv2. INTER_LINEAR，</p><p>“CUBIC”: cv2. INTER_CUBIC,</p><p>“LANCZOS”: cv2. INTER_LANCZOS4,</p><p>｝</p><p>#draw original image</p><p>plt. imshow(image[1500:2500, 5000:6000])</p><p>for algo in algos：</p><p># downsample the original image with selected algorithm</p><p>image_resized = cv2．resize(image, (736, 410), interpolation=algos[algo])</p><p>#draw results</p><p>plt. imshow(image_resized[150:250, 500:600])</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oppr0L0BJxmlNzBa.jpg" /></figure><p>For downsampling, the “area” algorithm looks best. It produces minimal noise and artifacts. In fact, it is OpenCV’s first choice for downsampling.</p><p>Now let’s do upsampling — restore the sampled image to its original size and see which algorithm works best in this case.</p><p># create downsampled image with preferred “area” algorithm</p><p>image_downsampled = cv2．resize(image, (736, 410), interpolation=cv2.INTER_AREA)</p><p>#draw original image</p><p>plt. imshow(image[1500:2500, 5000:6000])</p><p>for algo in algos：</p><p># upsample the downsampled image back to the original size</p><p># with the selected resizing algorithm</p><p>image_resized = cv2．resize(</p><p>image_downsampled，</p><p>(7360, 4100),</p><p>interpolation=algos［algo］</p><p>)</p><p>#draw results</p><p>plt. imshow(image_resized[1500:2500, 5000:6000])</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nLiV8POJ1ap72gLu.jpg" /></figure><p>For upsampling, the algorithm produces more consistent results. Still, “cubic” interpolation looks the least blurry and closest to the original (“lanczos” provides similar results, but is much slower).</p><p>So the final conclusion here is to use “area” interpolation for downsampling and “cubic” algorithm for upsampling.</p><p>Note that correct adjustment algorithm selection is also important during training as it can improve overall image quality. More importantly, the tuning algorithm for the training and inference phases should be the same, otherwise the model may have problems.</p><p><strong>in conclusion</strong></p><p>This article describes real-life cases and problems that have been encountered many times during many years of working in the field of computer vision. If not handled properly, each of them can significantly reduce model quality in production.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b25ec44be3e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Engineering book]]></title>
            <link>https://medium.com/@reza_mahmoudi/machine-learning-engineering-book-4fae66dbb5c0?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fae66dbb5c0</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 15:29:13 GMT</pubDate>
            <atom:updated>2023-11-24T15:29:13.869Z</atom:updated>
            <content:encoded><![CDATA[<p>Chapter 2 — Your data science could use some engineering</p><ul><li>ML engineering involves a trinity of core concepts</li><li>Tech (tools, frameworks, algos)</li><li>People (collaborative work, communication)</li><li>Process (development standards, experimentation rigor, Agile)</li><li>Three components of data science</li><li>Design — how data is going to be collected and in what structure it will need to be to solve the problem</li><li>Collection — Act of acquiring data</li><li>Analysis — Gaining insights from data through stats</li><li>Modern data science is largely based on the third piece — analysis — while a data engineering team handles the first two.</li><li>Data science (e.g. the ‘analysis’ above) is just one component of ML engineering. Other components include:</li><li>Project planning</li><li>Communication</li><li>Monitoring and evaluation</li><li>Software development</li><li>Model and artifact management</li><li>Scalability</li><li>Platform and deployment</li><li>Simplicity is the foundation of ML engineering — start with the most simple solution and add complexity from there as needed. Simplicity is “by far the single most important aspect of ML engineering.”</li><li>“Unfortunately for newcomers to the field, many data scientists believe that they are providing value to a company only when they are using the latest and “greatest” tech that comes along. Instead of focusing on the latest buzz surrounding a new approach catalogued in a seminal whitepaper or advertised heavily in a blog post, a seasoned DS realizes that the only thing that really matters is the act of solving problems, regardless of methodology. As exciting as new technology and approaches are, the effectiveness of a DS team is measured in the quality, stability, and cost of a solution it provides.”</li><li>Guide for building the simplest ML solution possible (this image seems ‘pin up next to your desk’ worthy — I’d imagine tons of time, energy, and money could have been saved if everyone walked through these steps first when approaching a project)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ae9KjUj2WsanAK1Q" /></figure><ul><li>Hypothetical complaint: “but it’s not data science work if the solution doesn’t use AI”</li><li>Ben never had the demoralizing experience regarding infrequent application of cutting-edge techniques, because he started in data analytics before moving to ML.</li><li>One of the biggest drivers of his focus on simplicity was the fact that it was his responsibility to maintain the solution. Using a more complex solution than was needed would unnecessarily complicate his job. Takes longer to diagnose failures, harder to troubleshoot, frustrating to change internal logic for new feature incorporation, etc.</li><li>Less time spent maintaining solutions = more time spent building new solutions = more value provided to the business</li><li>“Sometimes working on the basic things that bring incredible value to a company can help you keep your job (which isn’t to say that forecasting, churn, and fraud modeling are simple, even if they don’t seem particularly interesting).”</li></ul><p>This discussion of simplicity caused some pretty deep personal reflection for me. I am glad I encountered these ideas at this very early stage in my programming journey, because I think I am very prone to the trap that Ben sheds light on. I’d like to discuss a few examples, lessons learned, etc.</p><p>I work with a public-equity focused investment firm. Firms above a certain size need to file something called a 13-F, which is basically a list of the stocks that they own. Combing through 13-Fs of firms you respect can be a good way to find investment ideas. I had a couple of ideas of tools to build to make better use of these filings.</p><p>The firm I work for has a list of what we consider to be the best companies in the world, which we refer to as the SCM 100 list and serves as the shopping list for our fund. One project would essentially be something along the lines of “if &gt; x% of the 13-F filer’s portfolio is in names that are on our SCM 100 list, then show us other names from that portfolio that aren’t on the SCM100 or we haven’t chosen for exclusion from it.” This essentially creates a list of companies that we haven’t look at, but that are owned by investment firms that take a similar approach to us. Sourcing this way could effectively give us a higher “hit rate” in terms of what percentage of companies our research team looks at actually end up on our SCM 100 list. This increases the efficiency of the research team, which is one of our firm’s most important/expensive assets.</p><p>But when I considered whether to try building this side project, one of the things that came to mind was, “this is just a simple rules-based program, what is so exciting about that?” This deterred me from wanting to pursue it, and I am now starting to see that this was probably a mistake. There are other issues too — such as whether I have time to do this, whether I have/would be allocated the necessary amount of compute required to comb the whole database in this way, etc. But the fact that this didn’t use cutting edge ML should not have been a deterrent to me. I think that was my ego getting in the way. Another idea, that I surely have the compute to execute but is just a question of personal time allocation, is to make a list of all the holdings of e.g. 10 funds I really respect and show which they added to or trimmed that quarter, what the low price of that quarter was vs. the current price so I can evaluate signal value, etc.</p><p>There is a balance to strike between whether you are just providing value to the business vs. doing something you actually enjoy. For me, in this particular situation, I think there is enough of interest to me (refining my basic coding skills, having the actual tool once it is done to help me find new ideas, etc.) to make it worth pursuing. But if your more simplistic, business problem focused tasks sound deathly boring to you and you never want to do anything other than work on cutting edge AI models… well then maybe you should try to get a spot at Anthropic or the Stanford AI Lab. And that’s okay. There’s nothing wrong with that. But know that if you are part of a small data science team serving a business that focuses on something other than cutting-edge AI, there may be times where you do things that aren’t as interesting to you.</p><p>Another lesson I learned is that I should be more willing to embrace small projects, if nothing else than as a way to establish credibility. We recently decided to build an automated email alert that would send the research team an email whenever one of the stocks on our SCM 100 list hit the low end of our estimated valuation range, indicating it was potentially actionable. Our lone data scientist ended up spending some time to construct this. While it may have taken me a bit longer, I think that I should have taken this responsibility on my own. Not only would it help establish my credibility on the data side, but our PhD data scientist certainly had higher uses of his time that were a better match for his skillset if I could have taken this off of his plate.</p><p>Along these lines, I recently interviewed a potential candidate for a full-time data engineer position at our firm. He said something that really caught my eye. It was pretty off-the-cuff for him and I am not sure how much he thought about it. But I thought it spoke volumes about his character and clarity. He was explaining to me what his role as a data engineer consisted of and how he interfaced with the data scientists/ML engineers. He said something along the lines of, “My job is basically just to spare them from having to work with SQL so they can focus on the more complicated modeling work… basically, <strong>let the big dogs eat</strong>.” This reflected not only a team-oriented mindset, but a humble confidence in his mastery of his own role and skillset, as ell as a conviction about the value it provided to the firm.</p><p>I think that right now, I need to keep in mind the idea of a simple solution still providing value to the team. That is probably my highest possible route of value-add on the data science side of our firm. Because it will never be our PhD’s highest use of time to do something that doesn’t involve ML. To whatever degree I can step into those situations and free him up to work on more important stuff, I am providing value. Or even by just doing stuff he would’ve never gotten around to but that still provides value on the research side.</p><p>Back to the Ch 2 notes…</p><ul><li>Communication and cooperation are key — both internally amongst the ML team as well as with other business stakeholders for whom the solution is being built.</li><li>“Approaching project work with a lone-wolf mentality (as has been the focus for most people throughout their academic careers) is counterproductive to solving a difficult problem.”</li><li>Cooperation leads to you building the correct, useful solution faster than you otherwise would have</li><li>Embracing and expecting change is important. If you plan for change and expect it, you can focus on what is most important: solving problems. It helps alleviate any unnecessary attachment to certain approaches or methods. It also forces the project into a “modular format of loosely coupled pieces of functionality”.</li><li>“ML engineering brings the core functional capabilities of a data scientist, a data engineer, and a software engineer into a hybrid role that supports the creation of ML solutions focused on solving a problem through the rigors of professional software development.”</li></ul><p>This discussion of simplicity caused some pretty deep personal reflection for me. I am glad I encountered these ideas at this very early stage in my programming journey, because I think I am very prone to the trap that Ben sheds light on. I’d like to discuss a few examples, lessons learned, etc.</p><p>I work with a public-equity focused investment firm. Firms above a certain size need to file something called a 13-F, which is basically a list of the stocks that they own. Combing through 13-Fs of firms you respect can be a good way to find investment ideas. I had a couple of ideas of tools to build to make better use of these filings.</p><p>The firm I work for has a list of what we consider to be the best companies in the world, which we refer to as the SCM 100 list and serves as the shopping list for our fund. One project would essentially be something along the lines of “if &gt; x% of the 13-F filer’s portfolio is in names that are on our SCM 100 list, then show us other names from that portfolio that aren’t on the SCM100 or we haven’t chosen for exclusion from it.” This essentially creates a list of companies that we haven’t look at, but that are owned by investment firms that take a similar approach to us. Sourcing this way could effectively give us a higher “hit rate” in terms of what percentage of companies our research team looks at actually end up on our SCM 100 list. This increases the efficiency of the research team, which is one of our firm’s most important/expensive assets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fae66dbb5c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Challenges of machine learning systems in production]]></title>
            <link>https://medium.com/@reza_mahmoudi/challenges-of-machine-learning-systems-in-production-23e15426f70f?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/23e15426f70f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 08:36:07 GMT</pubDate>
            <atom:updated>2023-11-21T08:36:07.907Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning and deep learning have become rapidly popular in the past few years.</p><p>However, most of the information on the Internet and the teaching in the classroom focus on building models and adjusting models.</p><p>However, in actual production,</p><p>The responsibilities of a machine learning engineer are not only to build and maintain models, but also need to master some software engineering skills.</p><p>Most companies have only started using machine learning technology or developing related systems in the past few years.</p><p>There are even fewer companies that develop and operate machine learning systems on a large scale.</p><p>When running a system, you often encounter some challenges. This article wants to discuss in depth several challenges of running a machine learning system.</p><p>1. Organize the machine learning experiment process</p><p>Machine learning development is an iterative process.</p><p>Requires experimentation with multiple combinations of data, learning algorithms, and model parameters,</p><p>and track the impact of these changes on forecast performance.</p><p>Over time, this iterative experimentation can result in thousands of model training runs and model versions.</p><p>This makes it difficult to track the best-performing models and their configurations that feed into the best models.</p><p>As with traditional software engineering, few people develop models over time.</p><p>Team turnover, changes in goals, and changes to new data sets and features are common.</p><p>Therefore, we should expect that the experimental process of building the model will continue long after the model is first built.</p><p>It will become increasingly difficult to compare current experimental results with past experimental results to identify opportunities for further improvement,</p><p>This requires a system to track experimental metadata and the impact of different parameters on prediction performance.</p><p>2. Tuning and training the model</p><p>When training a model in an interactive programming environment such as Jupyter Notebook, debugging the model training job is a simple matter.</p><p>Run the code manually and if a training error occurs, the Jupyter notebook will show exceptions and stack traces.</p><p>If training is successful, a visual learning curve and other metrics can also be displayed.</p><p>Further diagnose whether the model has problems such as overfitting or gradient disappearance.</p><p>But when the model is processed in batches automatically over a fixed period of time, it becomes difficult to adjust the model.</p><p>While schedulers re-run failed training processes, they cannot easily check for issues like overfitting and vanishing gradients unless a custom solution is written.</p><p>And as data science teams aim to deploy more and more models, this problem will only gradually worsen as more and more models appear in the process.</p><p>3. Deploy the model to production environment</p><p>A machine learning model can only start adding value to a company when it satisfies its users.</p><p>The process of taking a trained ML model and making its predictions available to users or other systems is called “deployment.”</p><p>Deployment is completely different from regular machine learning tasks such as feature engineering, model selection, or model evaluation.</p><p>Therefore, data scientists and ML engineers who lack software engineering or DevOps background may not know much about this kind of deployment.</p><p>When deciding how to deploy a machine learning model, there are several factors to consider:</p><p>- How often forecasts should be generated.</p><p>- Whether predictions should be generated for a single instance at a time or for a batch of instances.</p><p>- Number of access model applications.</p><p>- Latency requirements for these applications.</p><p>4. Expand machine learning services</p><p>If models have been deployed to endpoints, they can start providing value to users.</p><p>But model endpoints may face higher workloads in the near future.</p><p>For example, if a company starts serving more users, these increased demands may reduce the quality of your machine learning service.</p><p>ML models hosted as API endpoints often need to respond to this change in requirements.</p><p>When requests increase, the number of compute instances serving the model should be increased, and when workload decreases, compute instances should be removed so that you don’t have to pay for instances that are not used.</p><p>5. Monitoring of models</p><p>This stage is the real beginning.</p><p>When the model is deployed on the platform, it is also important to monitor the predictions and anomalies of the model.</p><p>This stage must continuously monitor the model to detect and eliminate deviations in model quality, such as data drift.</p><p>Proactively detecting these deviations early enables corrective actions such as retraining the model, auditing upstream systems, or fixing data quality issues without having to manually monitor the model or build additional tooling.</p><p>Write at the end:</p><p>Sometimes it’s a good choice to avoid building your own machine learning infrastructure.</p><p>Leverage a broad range of open source tools and platforms to build models that deliver differentiated value.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e15426f70f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine learning in production]]></title>
            <link>https://medium.com/@reza_mahmoudi/machine-learning-in-production-d7ddca981832?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7ddca981832</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 13:39:10 GMT</pubDate>
            <atom:updated>2023-11-05T13:39:10.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning in production</p><p>Front Matter — Overview of the Book</p><ul><li>This book isn’t focused on algorithms, theories, or why one model is better than another for a particular use case. It’s about avoiding the pitfalls that end up derailing so many ML projects.</li><li>I’d be curious to hear what everyone’s top recommendations (books or authors) are for the other sort of book that is more focused on getting into the modeling weeds and solving individual problems.</li><li>Part 1 (chapters 1–8) — Management of ML projects. Scoping, experimentation, prototyping, feedback, etc.</li><li>Part 2 (chapters 9–13) — Development process. Building, tuning, logging, and evaluating a solution in a way that ensures you are building the simplest and most maintainable code possible.</li><li>Part 3 (chapters 14–16) — “the after”. Streamlining production release, retraining, monitoring, attribution, etc. Includes examples with A/B testing, features stores, a passive retraining system, and more.</li></ul><p>Chapter 1 — What is a machine learning engineer?</p><ul><li>The roadmap covered throughout the book:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/0*xy01exygz43XacUo" /></figure><ul><li>By embracing the above concepts, developing a solution can be shorter, cheaper, and have a higher probability of success.</li><li>Ben’s estimates of the six primary reasons projects fail</li><li>Planning — 30%</li><li>Scoping — 25%</li><li>Tech — 15%</li><li>Fragility — 15%</li><li>Cost — 10%</li><li>Hubris — 5%</li><li>Detours to watch out for along each step of the way</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/0*CMKrNj7_xI7HUCRn" /></figure><ul><li>Planning</li><li>Helps avoid solving the wrong problem</li><li>A lot of this, as with some of the other steps, involves working with the business unit to help better understand the goal. Gives an example of an executive telling the DS team that they need a higher email click rate. Could result in the DS team building an entire system for custom email recommendations, when maybe all they really wanted was just for emails to be sent at a time when clients are most likely to open them.</li><li>Scoping and research</li><li>You need to research and evaluate potential solutions and estimate how long they would take to implement and what exactly the work would consist of. Gives two examples, at opposite extremes, of how this could mess up. You have a team building a fraud detection solution and:</li><li>One possibility is that a team of very junior data scientists rushes to get the research done, quickly finds a blog post about XGBoost or fraud detection and decides to implement that. They do so in a rushed manner. The false-positive and false-negative rates are both too high and the model is useless.</li><li>Another possibility is a team of academia-focused researchers starts digging in to IEEE, arXiv, trade journals, etc. for two weeks. This is a good start. They decide to focus on a cutting edge idea. There is no package out there for it, so they need to implement what they found in the paper from scratch. Now you not only need to build and own the ML solution, but the algorithm as well. They come to eventually find out that they do not have the time or monetary budget needed to make it work.</li><li>“Some are academics whose sole goal is to further the advancement of knowledge and research into algorithms, paving the way for future discoveries from within the industry. Others are “applications of ML” engineers who just want to use ML as a tool to solve a business problem. It’s important to embrace and balance both aspects of these philosophies toward ML work”</li><li>Side note — I just listened to a very good podcast about Stripe’s fraud detection system. It feels like this would be a pretty reasonable place to start and to model the approach after? Is there really more digging required after this? Blog post <a href="https://stripe.com/blog/how-we-built-it-stripe-radar">https://stripe.com/blog/how-we-built-it-stripe-radar</a> and podcast <a href="https://thegradientpub.substack.com/p/ryan-drapeau-battling-fraud-with#details">https://thegradientpub.substack.com/p/ryan-drapeau-battling-fraud-with#details</a></li><li>Experimentation</li><li>You don’t want to do too much (takes forever to get rolling) or too little (you don’t find the best solution).</li><li>Gives another example of polar opposite ways to mess this up. Let’s say you are trying to come up with an image classification system to identify inventory on shelves.</li><li>The quick way — find a blog that shows how to use a pretrained CNN to classify dogs and cats. Take two products, unlock the last 25% of the network for relearning, and train it on the two products. It ends up working pretty well on these two products, but when you implement it, you find that the learned attributes are product color and pattern. It’s useless.</li><li>Spend two weeks researching and vetting options. Again, this is a good and necessary first step. But then they end up testing three different approaches, 1) 6–20 convolution and pooling layer CNNs, 2) transfer learning of three most probable pretrained large networks, and 3) semi-supervised discriminator GAN. This testing process takes forever and is costly. They end up working on all three for so long that overdeveloped experiments become MVPs. Their merits are indistinguishable in their results because each has been developed so much. They blew through all that budget and the project ends up getting cancelled due to cost. “This is far more common than you might think. I’ve seen this happen many dozens of times.”</li><li>Development</li><li>Code quality matters. Having a fragile code base and poor dev practices can make a project more difficult, make it easier to break in production, and harder to improve over time.</li><li>Discusses monolithic code bases vs modularized code bases. This was kind of a learning point for me. I had always wondered why, when I look at projects on GitHub, the scripts are broken down into so many different pieces. I guess this is basically the reason, this modularization benefit. It not only reduces the searching and scrolling you have to do, but it makes for easier/less problematic code merges when more than one person is working on the code base.</li><li>Coding with the assistance of e.g. GPT is similar in the sense of — I feel like you can only instruct it to do so much at once. Same with e.g. code review . I have seen people recommend only submitting small chunks of code at a time for the reviewer so they don’t get overwhelmed. The question, whether monolithic or not, is — what are the dependencies (if that’s the right word)? E.g. does changing one thing somewhere in the script — whether modularized or not — cause it to break somewhere else?</li><li>Deployment</li><li>“Not planning a project around a deployment strategy is like having a dinner party without knowing how many guests are showing up. You’ll either be wasting money or ruining experiences.”</li><li>You don’t want to be using unnecessarily complex or expensive deployment tools and infra, but you also want to make sure you have what you need to be able to execute.</li><li>Always strive the simplest design possible when building an architecture. “If the project requires a periodicity of inference of one week, use a batch process (not real-time streaming). If the data volumes are in the megabytes, use a database and a simple virtual machine (not a 25-node Apache Spark cluster). If the runtime of training is measured in minutes, stick to CPUs (not GPUs).”</li><li>What you don’t want, is to spend months building a project and then shut it off because you realize the production cost is too high.</li><li>Evaluation</li><li>You must be able to justify the benefits of your project staying in production. What value does it provide to the business?</li><li>If it only costs a couple hundred dollars to run, maybe this isn’t an issue. But if it’s a notable line item in the company’s expenses, at some point, someone will ask, “Is this $50,000/year ML project really providing us at least $50,000/year in value?”</li><li>Model attribution through A/B testing is one possible approach to this problem</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/0*iWhSr1oDzVQTJM-5" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7ddca981832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to the whole process of AI model production — model deployment matters]]></title>
            <link>https://medium.com/@reza_mahmoudi/introduction-to-the-whole-process-of-ai-model-production-model-deployment-matters-6040d46e0c31?source=rss-d7c286d9052d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6040d46e0c31</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[Reza Mahmoudi]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 11:07:28 GMT</pubDate>
            <atom:updated>2023-10-16T11:07:28.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to the whole process of AI model production — model deployment matters</h3><p>When I first entered the AI ​​industry, I was confused. I didn’t understand the various proper nouns for the production process of various AI models, let alone explain this process. There is currently very little information on the Internet that is for technical students. the entire process of AI model production is explained clearly, and more is discussed about the technology in each specific link. For a new student or a non-technical student, it is a very painful thing to understand the model deployment process of the entire AI model production process, so I want to make a series of related content that I have learned since I started. , I hope I can explain this process clearly, and also provide a foundation for my own learning process, so that I can better support the business in the future~</p><p><strong>What kind of content will this article contain?</strong></p><ol><li>First of all, the content of this article does not involve discussion of specific technologies at all.</li><li>Introducing the entire process of AI model production</li><li>Introduction to the process of model deployment</li></ol><h3>Concept explanation: model? algorithm? network?</h3><p>AI models specifically refer to models that use <a href="https://link.zhihu.com/?target=https%3A//www.paddlepaddle.org.cn/tutorials/projectdetail/3520300">neural networks</a> as parameter structures for optimization and ultimately have a specific role. I don’t know if you had such doubts when you first came into contact with the concept of AI models. Models, algorithms and networks are often mixed together, and often seem to be used interchangeably. I think the following concepts about networks, models and algorithms are explained relatively clearly.</p><ul><li>Network: A simple network structure that does not contain any weight parameters.</li><li>Model: After designing a network, train it on certain data sets to obtain data containing weight parameters, which is called a model.</li><li>Algorithm: Based on the model, certain related purposes are specifically achieved through some codes. These codes, model files and other resources are called an algorithm.</li></ul><h3>Where does AI model production sit on the AI ​​industry map?</h3><p>AI ( <strong>Artificial intelligence:</strong> artificial intelligence) refers to <strong>systems and machines that can imitate human intelligence</strong> to perform tasks and iteratively improve themselves based on collected information . For the artificial intelligence industry map, please refer to the figure below.</p><p>We generally come into contact with more AI-related content at the artificial intelligence application layer. For example: face recognition function, intelligent voice dialogue function, unmanned retail, etc. These are specific applications of AI technology in actual industries. These AI technologies are generally divided into: Artificial intelligence can be divided into computer vision (CV), speech recognition, natural language processing (NLP), and the now popular knowledge graph, etc. For example, face recognition belongs to the field of CV technology. The application of these AI technologies is inseparable from specific AI models. <strong>The AI ​​model production process</strong> belongs to the basic layer of artificial intelligence and is the basis for these upper-layer applications. AI basic layer = algorithm (AI model) + data + computing power.</p><h3>AI model production process</h3><p>What are the steps to produce a specific AI model? Let’s take a specific example to illustrate the entire process. What I hope to achieve is: inputting a picture of a film and television star can help me output the name of the star. The AI ​​model production process can be divided into the following six steps:</p><p><strong>1. Determine the purpose</strong> :First of all, you must understand that AI is just a technology, a tool that helps you achieve some of the functions you want. So the first step is to clearly know what problem you want to solve through AI? What is the business purpose. Only then can you know which AI technology and development ideas you need to look for.What I hope to achieve is: inputting a picture of a film and television star can help me output the name of the star. Break down this requirement: It is actually a simple <strong>image classification</strong> problem. Image classification is a specific scenario in computer vision.</p><p><strong>2. Prepare data</strong>Data preparation mainly refers to the process of <strong>collecting and preprocessing data</strong> . Purposeful collection and integration of relevant data according to the determined analysis purpose. Data preparation is a foundation for AI development. The most important thing at this time is to ensure the authenticity and reliability of the data obtained. In fact, it is not possible to collect all the data at once. Therefore, during the data annotation stage, you may find that a certain part of the data source is missing and make repeated adjustments and optimizations.</p><p>In this example, you first need to download a large number of pictures of celebrities from the Internet (all pictures related to the celebrities you want to identify). At this time, what you get is a large amount of irregular picture data, which can be of any size and format. Different; then you need to process the data: including data annotation (in this example, each picture needs to be marked with the star it represents), standardization of the pictures (same size and format), and data cleaning (possibly Download some pictures that are not celebrities and remove them), and you will get a <strong>standard data set</strong> ; the subsequent steps are not necessary. If you have fewer pictures, you can enrich them by cropping, rotating, etc. , can also improve the accuracy of subsequent models, because the input picture may be an upside-down picture.</p><p><strong>3. Model design &amp; algorithm selection</strong>Model network structure design is equivalent to the hypothesis space of the model, that is, the set of relationships that the model can express. The process is to assume a network structure, design its evaluation function (Loss), and then find an optimal solution method. In fact, there is no need to start model structure design from scratch in today’s AI business, because there are currently various excellent AI experts who have designed various classic algorithms to solve certain specific problems in practice. For example, algorithms that solve image classification problems include: AlexNet, GoogleNet, ResNet, MobileNet, ShuffleNet, VGG and other classic algorithms.Therefore, the existing model structure design generally selects a specific algorithm, and there are many open source algorithm libraries that have already helped everyone realize the specific implementation of the algorithm in advance. At present, model design is more of an algorithm selection. Choose an algorithm that suits your business and fine-tune the structure. Currently, open source algorithm libraries in the field of computer vision include OpenMMLab and Transformer’s open source algorithm library Hugging face.</p><p>The problem of film and television star recognition is actually a multi-image classification problem. We can choose an image classification algorithm.<strong>4. Training and evaluating models</strong>In addition to data and algorithms, what is more important is the design of model parameters. <strong>The parameters</strong> of model training directly affect the accuracy of the model and the model convergence time, and the selection of parameters greatly depends on the developer’s experience. Improper parameter selection will cause the model accuracy to fail to achieve the expected results, or the model training time will be greatly increased. That’s why everyone jokes that algorithm engineers are parameter adjusters.The result of training a model is usually one or more machine learning or deep learning models. The model can be applied to new data to obtain prediction, evaluation and other results. After training the model, the model needs to be evaluated and inspected. It is often not possible to obtain a satisfactory model at one time. It is necessary to repeatedly adjust algorithm parameters and data, and continuously evaluate the model generated by training. Some commonly used indicators, such as accuracy, recall, AUC, etc., can help you effectively evaluate and ultimately obtain a satisfactory model.Currently, there are various open source training frameworks on the market for everyone to choose from. For example: Pytorch, TensorFlow, MxNet, Caffe, <a href="http://etc.in/">etc.In</a> this example, the model evaluation criterion in the picture classification scenario is accuracy, that is, if the model is given a labeled photo of Wang Yibo, the model’s prediction result should be Wang Yibo, not other celebrities.</p><p><strong>5. Model deployment</strong>After the model is trained, it comes to the last step of the practical application of the AI ​​model — -model deployment. Model deployment is to deploy the trained model to actual application scenarios, so model deployment is more of an engineering process, which is to solve actual model application problems.The process of model deployment is as follows:</p><p><strong>1. Model format conversion:</strong>First, the models trained by researchers through various training frameworks generally need to be adapted to the model format. For model training, you can choose a variety of different training frameworks, such as TensorFlow, Pytorch, Caffe and a series of open source frameworks. The model formats trained by so many different training frameworks have their own standards and are different. The first problem to be solved in deployment is to adapt to various model formats. However, if you need to adapt the training frameworks to the formats one by one, the workload is too large and it is not suitable for expansion. Therefore, Microsoft has joined forces with Facebook and other major manufacturers to launch an intermediate format ONNX, hoping to solve the problem of adapting multiple model formats, that is, regardless of What is the model format trained by the training framework? It is ultimately deployed in the ONNX format. Therefore, the first step to solve in general model deployment is model format conversion.</p><p><strong>2. Model compression</strong>Model compression is <strong>to streamline the already trained deep model to obtain a lightweight and accurate network. The</strong> compressed network has a smaller structure and fewer parameters, which can effectively reduce calculation and storage. Overhead, easy to deploy in constrained hardware environments.During training, because forward and backward propagation must be ensured, each gradient update is very small. At this time, relatively high precision is required. Generally speaking, float type, such as FP32, 32-bit floating point type is required to process data, but During inference, the accuracy requirements are not that high. Many studies have shown that low precision can be used, such as a half-length (16) float type, that is, FP16, or an 8-bit integer type (INT8). Inference. Therefore, generally speaking, the model will be compressed when it is deployed. Model compression methods include: distillation, pruning, quantization, etc.</p><p><strong>3. Model reasoning and pre- and post-processing</strong> <strong>Pre-processing</strong> : Because the input of model reasoning is Tensor (multi-dimensional matrix) data, but the input of normal AI applications are pictures, videos, text and other data, so <strong>pre-processing is to convert the input data of the business ( Images, videos, text, etc.) are pre-processed into data that can be received by model reasoning — -Tensor (multidimensional matrix)</strong> . Taking image processing as an example, pre-processing actions include but are not limited to: image format conversion, color space transformation, image transformation (resize, warpaffine (affine transformation)), image filtering and other operations. OpenCV is an open source cross-platform computer vision library launched by Intel. <a href="https://github.com/opencv/opencv">https://github.com/opencv/opencv</a></p><p><strong>Model inference</strong> : Model inference should be the core part of the model deployment pipeline. <strong>It is necessary to run</strong> the actual input data (after conversion into Tensor data) in the trained model in the actual application environment (specific deployment equipment) , and achieve the expected results in business indicators such as performance and accuracy. This process includes the adaptation of the deployment device (CPU/GPU/DSP/NPU). If you want to run the model on any kind of device, you need to adapt to the device in advance, and you must also ensure performance and accuracy and other indicators. . This is a very complicated process, and I hope to introduce it in detail in a follow-up article. There are many open source deep learning inference frameworks on the market that solve problems related to model inference. For example: Open source inference frameworks launched by major domestic manufacturers: OpenPPL, TNN, MNN, Tengine, etc., as well as TensorRT launched by NVIDIA for GPU cards, Intel’s OpenVINO for Intel chips, etc. <strong>Post-processing</strong> : It is to convert the Tensor data after model inference into feature data that can be identified by the business (different businesses will present different final effect data).</p><p>To summarize: the process of model inference and pre- and post-processing:</p><ul><li>step1:PreProcess(Image -&gt; Tensor)</li><li>step2:NN Forword/Inference(Input Tensor -&gt; Output Tensor)</li><li>step3:PostProcess(Output Tensor -&gt; Annotation Data)。</li><li>4. Deployment SDK and integrated<strong>deployment SDK</strong> : It is necessary to package model reasoning and pre- and post-processing functions, and consider the implementation of license, model security (encryption and decryption) and other functions in actual applications, and finally enter a deployment SDK that is convenient for business parties to use.This is a stand-alone mode deployment, and now large-scale model deployment and public cloud deployment may be another form.<strong>Integration</strong> : It is implemented by engineering students from the specific business side. The deployment SDK is integrated into specific applications and called through interfaces according to actual business needs, ultimately achieving the effect of actual application of AI. For example: In the above example, whether the deployment SDK should be integrated into the mobile phone or the PC, whether it should be implemented through an app or a small program, and how to display the final effect, these are all implemented by the students of the specific business of the integration part.The entire process of AI model production has been introduced. There are not many advanced technical discussions, but the entire process is strung together to give everyone a comprehensive understanding of the AI ​​model production process. If there are any errors, please correct them!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6040d46e0c31" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>