Studying the potential of language model to translate source code from Java to Kotlin
Full text
id188803 STUDYING THE POTENTIAL OF LANGUAGE MODEL TO TRANSLATE SOURCE CODE FROM JAVA TO KOTLIN JAVIER ABELLA NIETO Thesis supervisor: MATÍASSEBASTIÁNMARTÍNEZMARTÍNEZ(DepartmentofServiceand InformationSystemEngineering) Thesis co-supervisor: CARLOSESCOLANOPEINADO(DepartmentofComputerScience) Degree:Bachelor'sDegreeinInformaticsEngineering(SoftwareEngineering,Computing) Bachelor's thesis Facultat d'Informàtica de Barcelona (FIB) Universitat Politècnica de Catalunya (UPC) - BarcelonaTech
1 Abstract This thesis investigates the use of language models for translating source code from Java to Kotlin, employing the JVM bytecode as an innovative intermediate representation. This novel approach addresses a gap in existing methodologies, as no previous studies have used bytecode in this manner for code translation. The primary aim was to evaluate the feasibility and effectiveness of this technique in enhancing the automation of the code translation process. The research involved a comprehensive review of the literature to establish a strong foundation and identify the limitations of current approaches. Building on this foundation, we developed a new model leveraging the architecture of TransCoder, adapted to support the intermediate use of bytecode. The experimental framework utilized Masked Language Modeling (MLM) to train the model, drawing on diverse datasets to improve its ability to generalize across programming languages. Throughout the experimental phase a variety of obstacles were found. Despite these obstacles, the study successfully demonstrated the potential of using bytecode as an intermediate language. The results showed significant promise, particularly in bytecode translation, although there were some inconsistencies in translating between Java and Kotlin. These findings underscore the potential of our innovative approach in handling complex code translation tasks. In conclusion, this research validates the innovative use of bytecode as an intermediate representation in code translation, contributing valuable insights to the field of automated software engineering. Our findings lay the groundwork for future studies and advancements in the development of robust, efficient code translation tools. 2
Resum Aquesta tesi investiga l’´us de models de llenguatge per traduir codi font de Java a Kotlin, utilitzant el bytecode JVM com una representaci´o interm`edia innovadora. Aquest nou enfocament aborda un buit en les metodologies existents, ja que cap estudi previ ha utilitzat bytecode d’aquesta manera per a la traducci´o de codi. L’objectiu principal era avaluar la viabilitat i l’efic`acia d’aquesta t`ecnica per millorar l’automatitzaci´o del proc´es de traducci´o de codi. La recerca va suposar una revisi´o exhaustiva de la literatura per establir una base s`olida i identificar les limitacions dels enfocaments actuals. Partint d’aquesta base, vam desenvolupar un nou model que aprofitava l’arquitectura de TransCoder, adaptat per donar suport a l’´us intermedi de bytecode. El marc experimental utilitza el Modelatge de Llenguatge M`ascara (MLM) per entrenar el model, basant-se en diversos conjunts de dades per millorar la seva capacitat de generalitzar a trav´es de llenguatges de programaci´o. Al llarg de la fase experimental es van trobar una varietat d’obstacles. Malgrat aquests obstacles, l’estudi va demostrar amb `exit el potencial d’utilitzar bytecode com a llenguatge intermedi. Els resultats van mostrar una promesa significativa, particularment en la traducci´o de bytecode, tot i que hi va haver algunes incoher`encies en la traducci´o entre Java i Kotlin. Aquests resultats posen de manifest el potencial del nostre enfocament innovador en la gesti´o de tasques complexes de traducci´o de codi. En conclusi´o, aquesta investigaci´o valida l’´us innovador del bytecode com a representaci´o interm`edia en la traducci´o de codi, aportant informaci´o valuosa en el camp de l’enginyeria de programari automatitzada. Els nostres descobriments estableixen les bases per a futurs estudis i aven¸cos en el desenvolupament d’eines de traducci´o de codi robustes i eficients. 3
Resumen Esta tesis investiga el uso de modelos de lenguaje para traducir c´odigo fuente de Java a Kotlin, utilizando lo bytecode JVM como una representaci´on intermedia innovadora. Este nuevo enfoque aborda un vac´ıo en las metodolog´ıas existentes, puesto que ning´un estudio previo ha utilizado bytecode de este modo para la traducci´on de c´odigo. El objetivo principal era evaluar la viabilidad y la eficacia de esta t´ecnica para mejorar la automatizaci´on del proceso de traducci´on de c´odigo. La investigaci´on supuso una revisi´on exhaustiva de la literatura para establecer una base s´olida e identificar las limitaciones de los enfoques actuales. Partiendo de esta base, desarrollamos un nuevo modelo que aprovechaba la arquitectura de TransCoder, adaptado para apoyar al uso intermedio de bytecode. El marco experimental utiliza el Modelado de Lenguaje M´ascara (MLM) para entrenar el modelo, bas´andose en varios conjuntos de datos para mejorar su capacidad de generalizar a trav´es de lenguajes de programaci´on. A lo largo de la fase experimental se encontraron una variedad de obst´aculos. A pesar de estos obst´aculos, el estudio demostr´o con ´exito el potencial de utilizar bytecode como lenguaje intermedio. Los resultados mostraron una promesa significativa, particularmente en la traducci´on de bytecode, a pesar de que hubo algunas incoherencias en la traducci´on entre Java y Kotlin. Estos resultados ponen de manifiesto el potencial de nuestro enfoque innovador en la gesti´on de tareas complejas de traducci´on de c´odigo. En conclusi´on, esta investigaci´on valida el uso innovador del bytecode como representaci´on intermedia en la traducci´on de c´odigo, aportando informaci´on valiosa en el campo de la ingenier´ıa de software automatizada. Nuestros hallazgos establecen las bases para futuros estudios y adelantos en el desarrollo de herramientas de traducci´on de c´odigo robustas y eficientes. 4
Contents 1 Abstract ............................................. 2 2 Introduction .......................................... 9 2.1 Contextoftheproject ................................... 9 2.2 Justification......................................... 9 2.3 Glossary........................................... 10 2.4 Objectives.......................................... 11 2.4.1 Mainobjective ................................... 11 2.4.2 Secondaryobjectives................................ 12 2.5 Stakeholders......................................... 13 2.6 Risks............................................. 14 2.7 Methodology ........................................ 14 2.7.1 Version Control System (VCS) . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3 Initial planning ......................................... 16 3.1 Membersoftheteam.................................... 16 3.2 Backlog ........................................... 16 3.2.1 GEP......................................... 17 3.2.2 Meetings ...................................... 18 3.2.3 Researchstudy................................... 18 3.2.4 Discusstheapproach................................ 18 3.2.5 Design the architecture and IDE set up . . . . . . . . . . . . . . . . . . . . . 18 3.2.6 Develop an initial prototype of the new model . . . . . . . . . . . . . . . . . 19 3.2.7 Test the initial prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3.2.8 Fine-tunning .................................... 19 3.2.9 Projectreport ................................... 19 3.2.10 Conduct final tests to ensure quality and reliability . . . . . . . . . . . . . . . 20 3.2.11 Review and close documentation and prepare the defense of the project . . . 20 3.3 Taskassignment ...................................... 21 3.4 Ganttdiagram ....................................... 23 4 Finance planning ....................................... 24 4.1 Costidentification ..................................... 24 4.1.1 Humancosts .................................... 24 4.1.2 Hardware and Software costs . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 4.1.3 Environmentalcosts ................................ 26 4.2 Deviationsandrisks .................................... 26 4.3 Totalcosts ......................................... 26 5
5 Sustainability .......................................... 27 5.1 Autoevaluation....................................... 27 5.1.1 Environment .................................... 27 5.1.2 Economics...................................... 28 5.1.3 Social ........................................ 29 6 Changes after GEP ...................................... 30 6.1 Resourcesused ....................................... 30 6.2 Planningtasks ....................................... 30 6.3 Ganttdiagram ....................................... 30 6.4 Finalcosts.......................................... 32 7 Research study ......................................... 33 7.1 Studiesanalysis....................................... 33 7.2 Researchtable ....................................... 38 7.3 Benchmarks......................................... 39 7.4 Datasets........................................... 42 8 Approach for Java to Kotlin translation ......................... 43 8.1 Approach .......................................... 43 8.2 Architecture of Transcoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 8.3 Training the encoder-decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 9 Experimental protocol .................................... 46 9.1 Experimentalsetup..................................... 46 9.1.1 Environmentalsetup................................ 46 9.1.2 Obtention of training dataset . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 9.1.3 Dataobtention................................... 46 9.1.4 Tranformation to Transcoder input format . . . . . . . . . . . . . . . . . . . . 49 9.2 Datapreprocessing..................................... 50 9.2.1 Java dataset preprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 9.2.2 Kotlin dataset preprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 9.2.3 Bytecode dataset preprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . 52 9.2.4 Sharedpreprocessing................................ 52 9.3 Executing Training Transcoder for Java to Kotlin . . . . . . . . . . . . . . . . . . . . 52 9.4 Validation of the trained model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 10 Problems and issues faced .................................. 57 11 Conclusions of the study ................................... 61 6
11.1Futurework......................................... 61 12 Achievement of Technical Competencies ......................... 63 12.1Softwarecompetencies................................... 63 12.2 Computer science competencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 13 Appendix ............................................ 69 A Github miner .......................................... 69 A.1 Fetchrepositorylanguage ................................. 69 A.2 MineKotlinprojects.................................... 69 B Project builder ......................................... 70 C Bytecode generator ...................................... 71 C.1 Organizingthefiles..................................... 71 C.2 Removing inconsistencies from dataset . . . . . . . . . . . . . . . . . . . . . . . . . . 71 C.3 Generate readable bytecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 D Data transformation script ................................. 72 D.1 Transforming the data into JSON format . . . . . . . . . . . . . . . . . . . . . . . . 72 D.2 Tranforming into JSON format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 D.3 Creating the JSONL files and convertion into Gzip . . . . . . . . . . . . . . . . . . . 73 E Preprocessing script for monolingual datasets ..................... 74 F Kotlin processor ........................................ 75 F.1 Initiation .......................................... 75 F.2 Processorfunctions..................................... 76 G Bytecode processor ...................................... 77 H Preprocessing script ..................................... 78 I Training script ......................................... 79 7
List of Figures 1 Initial Gantt diagram Source Self-made......................... 23 2 Sources of energy in Spain in March and the first trimester Source: amaranzero[21] ................................. 28 3 Final Gantt diagram Source Self-made ......................... 31 4 Java and Kotlin compilation diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 5 Illustration of the three principles of unsupervised machine translation used by TransCoder. Adapted from Lachaux et al. (2020)[12]. . . . . . . . . . . . . . . . . . 44 6 Example of ideal back-translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 7 Datapipeline ........................................ 47 8 GithubMinerAPIrequest ................................ 47 9 Repositorystructure.................................... 48 10 Java, Kotlin and Bytecode files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 11 Perplexityfirstvalues ................................... 54 12 Accuracy evolution during MLM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 13 Resultsoffirstepoch.................................... 56 14 Resultsoffourthepoch .................................. 57 15 Perplexity evolution in several epoch . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 16 Hashcreation........................................ 58 17 Isvalidfunction ...................................... 59 18 Changeofaliteral ..................................... 60 19 Datasummaryintraining................................. 60 8
2 Introduction My bachelor’s thesis “Studying the potential of language models to translate source code from Java to Kotlin” serves as the capstone for the Faculty of Informatics of Barcelona (FIB) Informatics Engineering program within the Software Engineering specialisation, complemented by a secondary emphasis in Computing. 2.1 Context of the project In the world of programming, languages are constantly evolving to improve factors like productivity, efficiency, scalability and security. Developers often need to move their apps from an older language to a newer one to keep up with these changes. Our study focuses on moving applications from Java to Kotlin. Java has been around for a long time and is known for its stability and ability to work across different platforms. Kotlin, on the other hand, is a newer language that combines the best parts of object-oriented and functional programming, which Java doesn’t fully offer [4]. Kotlin is interoperable with Java, meaning it both can run on the Java Virtual Machine (JVM), making it easy for the two languages to work together. This compatibility is a big reason why many developers are starting to prefer Kotlin over Java. Kotlin’s code is shorter and less likely to have errors, making it easier to maintain and update applications [22]. The move towards Kotlin has picked up, especially since Google recommended it for Android app development. This endorsement has sparked a lot of interest in converting old Java apps into Kotlin to take advantage of its modern features, such as easier ways to write asynchronous code, which makes apps run more smoothly and efficiently [7]. Currently, the most widely used tool for translating code from Java to Kotlin is the one integrated into Android Studio by JetBrains. However, this tool has limitations, as it does not produce high-quality code. This is due to its reliance on a rule-based translation system, which often results in generated code that lacks idiomatic expression and adherence to best practices in Kotlin. This study aims to look into how we can use language models to make this transition from Java to Kotlin easier and more efficient for developers. By examining existing tools and developing a new model, we hope to find better ways to automate the translation process, making it simpler for developers to upgrade their apps to Kotlin. 2.2 Justification I’ve chosen this topic for my bachelor’s thesis for several compelling reasons, with the main one being my desire to integrate the knowledge and skills I have acquired from two distinct specialties, Software Engineering and Computing, into my final project. Language models presented themselves as the perfect medium through which I could achieve this synthesis, sparking my interest in exploring their potential further. Consequently, I was drawn to the idea of utilising language models for a purpose that resonates with my academic journey, thus giving birth to this project. 9
3 Initial planning In this part of the document we will see how the tasks in the project are distributed among all the members of the team, an estimation for each task and the Gantt diagram which represents the time guide to follow. 3.1 Members of the team In order to begin with the distribution of the tasks we need to establish the members of the team which are the following: Project Manager The project manager is crucial in overseeing and coordinating the work effectively. Their primary duties involve strategically planning and managing the project’s milestones and deadlines to ensure timely and correct completion. Moreover, they are responsible for distributing the required resources, including human and technical, to ensure the project’s success. The manager’s ability to make strategic decisions and maintain an overall perspective of the project is vital for steering it on the correct path and achieving the set goals. Data researcher The data researcher plays a key role in analyzing and interpreting data to support informed decisionmaking. In this project will be the one that collect and analyze all the data from several studies that can be useful towards building the new model Machine Learning Engineer The Machine Learning engineer designs and implement machine learning models, fine-tune their performance, and integrate them into applications to solve complex problems. In this project will be responsible of supervising the outcome of the model. Helping in the fine-tuning if necessary and guiding the software engineer towards the best path possible. Junior Software Engineer The software engineer is the one who gets to do all the programming tasks, such as creating the model and fine-tuning it, as well as the documentation related to the translation tools that will be created in this project. 3.2 Backlog In this part will be explained every task in the project. All tasks to be carried out will be listed, along with its user stories (if applicable) and their estimation. 16
3.2.1 GEP The first task in the thesis is a set of four deliverables from the subject GEP 1, which is imparted by the FIB on all of the students that work in their final thesis. This subject aims to provide a small foundation of documentation on which the student can structurally build their thesis. This whole part took 120 h. c Context and scope In this first deliverable the student had to define which is the context of the thesis, including an introduction to the problem, a justification on why the project is done using one approach instead of another and identifying the stakeholders, what is within the scope and what is not, focusing on objectives and sub objectives, and the methodology which will be used throughout the project alongside with what risks can appear or which difficulties do we begin with. All of this took an amount of 40 hours. Time planning In the second deliverable the student had to elaborate all the task assignment with its user stories. Add a risk management with some alternative plan and then make a Gantt diagram with all of those tasks. This second deliverable took a little less than the previous one with an amount of 30 hours. Budget and sustainability This was the third and last deliverable with new sections added to the document from the GEP subject. In this deliverable the student had to create a finance planning with all kind of specifications, identifying all the costs of the project, creating a team that will work on it, estimating salaries of the team, costs of the environment and derivatives. This submission had to include also a brief report of sustainability and how is it covered with the project like having in mind the carbon footprint that the project will produce. For this deliverable the student had to research all of the costs and estimate them according tot he project, so it took an amount of 35 hours. Final deliverable This last deliverable consisted in correcting all the previous documents with the feedback given by the professor and then create the final document that will be finally evaluated. As this was the final deliverable, just the correction had to be done so it took an amount of 15 hours. 1Stands for Gesti´o de Projectes which translates into Project management 17
3.2.2 Meetings There would be a weekly meeting with the director, the co-director and the student where the student will show all if the improvements made in the last week, try to solve doubts and agree what will be the next step of the project for the following week, adapting the initial planning if necessary. All of the meetings alongside the project are estimated in 12 hours. 3.2.3 Research study This task consist in reviewing existing articles about language models and code translation tools that can be useful, and then do a brief summary of each article and turn all the data from the articles into useful information. Total estimation: 80 hours. Review existing articles on language models and code translation tools A research looking for some useful articles than can help the study follow the right path and make a foundation from where the project can grow. This is estimated to take about 30 hours Write a summary of each article Depends on the previous sub-task. From all the previous studies, there has to be a brief summary and classify in one of two categories, the article is valuable (adds some new information, new models or a new approach) or is not valuable (its similar to one already read or does not give new data nor information). This is estimated in 40 hours. Summary table Create a summary table with all the articles marked as valuable in the previous sub-task, including some of its main characteristics like, approach, data evaluation and models used. This is estimated in 10 hours. 3.2.4 Discuss the approach Discussing the approach that will be used in order to create the new code translation tool from Java to Kotlin based on the information learnt from the previous investigation with the director and co-director of the thesis, this includes also if whether use a completely new model or using an existing previous one and fine-tunning it using only Java to Kotlin translation. This task is estimated in 10 hours. 3.2.5 Design the architecture and IDE set up Make the planning and mapping for the translation tool using the approach selected from the previous task 3.2.4 and setting up the development environment needed for starting coding. This 18
is estimated in 40 hours. Design the architecture of the new model Defining the functional an non-functional requirements and choosing an architecture for the model. This is estimated in 30 hours. IDE setup Set up all of the software resources that will be needed alongside the project like a repository on GitHub, where he code will be located, the database that will be used to validate the model, the spaces that will be used to make the code. This is estimated to be done in 10 hours. 3.2.6 Develop an initial prototype of the new model Developing the initial‘prototype of the code translation tool capable of translating code from Java to Kotlin. This is estimated in 40 hours. 3.2.7 Test the initial prototype Testing the prototype with all kind of test, identify the issues, look after the feedback from the director and co-director. This is estimated in 25 hours. Testing the prototype Testing the prototype with a comprehensive suite of tests to ensure coverage of the majority of possible scenarios. Estimation: 10 hours Identify issues and feedback Using the results of tests, identify all the issues that the model can have as well as getting some feedback from the director and co-director to be used for the fine-tunning. Estimation 15 hours. 3.2.8 Fine-tunning With all the information gathered until now, fine-tunning the model trying to correct all of the issues, correcting weights and code to optimise the model performance, speed and scalability. This is estimated in 70 hours. 3.2.9 Project report Create all the documentation needed for the project, reporting all the steps of the project, explaining every one of them in depth. Estimation: 68 hours. 19
3.2.10 Conduct final tests to ensure quality and reliability Run the same tests and new ones to check all the issues have been fixed without adversely impacting the model. Estimated: 25 hours 3.2.11 Review and close documentation and prepare the defense of the project Check all the documentation to correct any kind of typo that could have been done by mistake, let the director and co-director read it before submit the documentation and prepare the presentation to defend the thesis in front of the jury. This is estimated in 50 hours. Check documentation Check all the documentation, being aware of possible typos, missing information or missing changes. Estimation: 10 hours. Approval from both the director and co-director Wait for the director and co-director to read and approve all the documentation for the thesis before its submission. Estimation: 20 hours Prepare the defense Design and rehearse the thesis defense in order to be fully capable of answering all the doubts that the jury can ask to the student. Estimation: 20 h 20
3.3 Task assignment In this section we can see a table with the assignation of all the tasks alongside with the resources that are required for each of them. 21
Tag Task name Time Dependecies Human resources Hardware and Software resources 1 GEP 120 h - - - 1.1 Context and scope 40 h - PM Laptop, Overleaf 1.2 Time planning 30 h - PM Laptop, Overleaf, Canva 1.3 Budget and sustainability 35 h 1.2 PM Laptop, Overleaf 1.4 Final deliverable 15 h 1.1, 1.2, 1.3 PM Laptop, Overleaf 2 Meetings 12 h - PM, DR, ML, SE Laptop, Google meet 3 Research Study 80 h - - - 3.1 Review existing articles 30 h - DR Laptop 3.2 Write a summary of each article 40 h 3.1 DR Laptop 3.3 Summary table 10 h 3.2 DR Laptop 4 Discuss the approach 10 h - PM, ML Google meet 5 Design the architecture and IDE set up 40 h - - - 5.1 Design the architecture of the new model 30 h 3.1 PM, ML, SE Laptop 5.2 IDE setup 10 h - SE Laptop 6 Develop an initial prototype of the new model 40 h 4.2 ML, SE Laptop 7 Test the intial prototype 25 h - - - 7.1 Testing the prototype 10 h 6 SE Laptop 7.2 Identify issues and feedback 15 h 6 ML,SE Laptop 8 Fine-tunning 70 h 7.2 SE Laptop 9 Project report 68 h - PM Laptop, Overleaf 10 Conduct final tests 25 h 8 SE Laptop, Overleaf 11 Final documentation 50 h - - - 11.1 Check documentation 10 h 9 PM Laptop, Overleaf 11.2 Documentation approval 20 h 11.1 PM,ML Laptop, Overleaf 11.3 Prepare the defense 20 h 11.2 PM Laptop Table 1: Task assignation by role. Source: Self-made 22
3.4 Gantt diagram Figure 1: Initial Gantt diagram Source Self-made 23
4 Finance planning In this section, we explore the budget, a critical component for outlining the financial requirements and constraints of the project. Establishing a comprehensive budget is crucial, as it lays the foundation for efficient resource allocation and ensures that the project remains financially viable throughout its development. By identifying anticipated costs and allocating funds accordingly, we aim to maintain a balance between ambition and financial realism, ensuring that the project’s objectives can be achieved within the set financial parameters. 4.1 Cost identification In the cost identification section, we outline the project’s financial requirements, focusing on human costs like salaries for developers and researchers, as well as computational resources needed for development and testing and lastly on the environmental costs such as electricity. This analysis aims to ensure financial viability and efficient resource allocation, supporting informed budget management. 4.1.1 Human costs In order to analyse the human costs we have to calculate the costs derivated from hiring a complete team that will develop the project. That means we need to estimate the salary of each member of the team which, we previously introduced briefly on the previous section. Project Manager In this project this role will be executed by the director of the thesis and the student who will be the ones that supervises the project the most. Being aware of the deadlines. Data Research In this project this role will be executed by the student, the author of the thesis, who has to gather the data from several studies and turn it into some useful information that helps the project. Machine Learning Engineer This role will be executed by the co-director of the thesis who is from the computing science so has more experience in the area of Machine learning. His main task is about supervising the creation of the new source code translation tool. Junior Software Engineer This role will also be executed by the student who has to create the new model following the instructions from both the Machine Learning engineer and the Project Manager, including all the documentation and corrections that comes with the tasks. 24
In the table ?? are described all the human costs per hour for each member of the team Role Gross cost per hour Social Security Total cost Project Manager 18,46 €5,53 €23,99 € Data Research 12,44 €3,7 €16,14 € Machine Learning Engineer 28,21 €8,46 €36,67 € Software Engineer Junior 15,23 €4,56 €19,79 € Table 2: Costs of the team based on the information of Talent.com. Source: Self-made Now we have the cost per hour of each member, so if we multiply each for the number of hours we get the cost for each member of the team. Role Cost per hour Tasks hours Total cost Project Manager 23,99 €270 6477,30 € Dara Research 16,14 €92 1484,88 € Machine Learning engineer 36,67 €127 4657,09 € Junior Software Engineer 19,79 €142 2810,18 € Environment - - 15429,45 € Table 3: Costs of the team based on the task distribution Source: Self-made 4.1.2 Hardware and Software costs Hardware: On the hardware side we are going to use a laptop ASUS VivoBook 16X which cost around 1000 €. The average life spam is about 3 to 5 years, We will be using the 4 years mark, the time that we will be using the laptop will be the duration of the project that is estimated in 450 hours. If we then calculate the laptop’s depreciation, using the formula such that: depreciation = total price ×hours used lifespan hours Using the formula we get a sum of 32.55 €of depreciation. So if we sell the laptop once the project is finished we could theoretically regain the Initial price - depreciation. But still we will count the 1000 €. Software On the Software side, as we said, we are going to use several resources that will help through the project, being more precise: Overleaf for documentation, Gihtub for the repository, Canvas for creating the Gantt diagram, hugging face for studying and discover new models, and Google Colab for coding. All of this resources are free then, its total cost is 0€. 25
6.4 Final costs Due to changes in the tasks, the human costs of the project were also affected. The varying requirements for team members involvement made the initial cost table obsolete, as some team members were needed more or less than originally anticipated. Role Cost per hour Tasks hours Total cost Project Manager 23,99 €275 6597,25 € Data Research 16,14 €112 1807,68 € Machine Learning engineer 36,67 €232 8507,44 € Junior Software Engineer 19,79 €242 4789,18 € Environment - - 21701,55 € Table 7: Final costs of the team based on the task distribution Source: Self-made After updating the human costs, it is necessary to review the total project cost. The revised total project cost can be seen in the following table: Cost identification Cost value Human costs 21701,55 € Hardware 1000 € Software 0 € Environment 948,43 € Risks Fund 2556,68 € Total 26206,66 € Table 8: Final project total budget Source: Self-made The final costs have been increased in 6272,1€due to all the changes and unexpected events alongside the project. 32
7 Research study In this section we present a background study. A research which intention is doing background checks for similar studies, and then, using the information from them to help us increase our knowledge on the area of study. From each article study we have found we have a brief summary of it, a brief explanation for whether the article is or not related to our study, and we conclude with a table summary with all of the most relevant studies for the project, including its most relevant characteristics. We also discuss all the benchmarks and datasets used for each one of the models we see in the following subsections 7.3 and 7.4. 7.1 Studies analysis In this first part we will see the research study, for each article will appear in order: the reference, a briefly summary of the article with its key aspects and then, a conclusion if the article or paper can be useful to our project. Codegeex: A pre-trained model for code generation with multilingual evaluations on humaneval-x [33] This paper presents a new model called CodeGeeX and a comparison in source code generation and source code translation between languages using different models, for instance In-Coder or CodeGen-Multi and of course CodeGeeX. The performance of these models has been evaluated using the HumanEval-X dataset [6]. One of CodeGeeX’s significant strengths is its ability to perform code translation tasks as evidenced by its integration into platforms like Visual Studio Code and JetBrains. Given that JetBrains is a common IDE for both Java and Kotlin development, the existing infrastructure and the model’s integration point towards a practical application in real-world scenarios. In conclusion, despite CodeGeeX has not been trained on Kotlin, then no supporting Java⇔Kotlin, its multilingual architecture counting with an amount of 23 different languages, coupled with extensive training on related languages and its proven integration capabilities in IDEs used for Kotlin development, makes it a promising candidate and for adaptation in Java to Kotlin translation tasks. Codescope: An execution-based multilingual multitask multidimensional benchmark for evaluating LLMs on code understanding and generation [32] Codescope is an innovative benchmark for a comprehensive analysis of capabilities of Large Language Models (LLMs) to understand and generate code across multiple programming languages, with a total of 43 languages. CodeScope distinguishes itself by the fact that it relies on executionbased measures for evaluating the efficiency of code, which is an improvement from usual standards 33
that mostly pay attention to syntax correctness without further evaluation. Its key features include as mentioned before the evaluation based on execution, evaluating the generated code’s practical usefulness by running it and checking if it functions as expected. Consequently, the approach does not only enable the code to be logically right but also make it be usable in a certain scenario. In conclusion for this project, CodeScope’s focus on executable code is particularly beneficial for translating between Java and Kotlin. It ensures that translations preserve not just the shape or meaning but also the function and correctness. Understanding the effectiveness of large language models in code translation [23] This paper presents an innovative approach to unsupervised machine translation using monolingual corpora only (data in only one language), a significant shift from traditional methods that rely heavily on parallel text data.4. For instance traditional translation models use parallel text data where sentences in one language are directly paired with their translations in another. For example, an English sentence would be paired with its Spanish translation, same applies to programming languages. This parallel structuring allows models to learn the linguistic intricacies of both languages involved. By contrast,This research aims to explore the feasibility of learning effective translation models without direct supervision, leveraging advanced neural network architectures and novel training techniques. The paper describes a sequence-to-sequence model that incorporates shared latent spaces and unsupervised learning techniques to perform translations without parallel corpora. The approach relies on iteratively improving translation models through a sophisticated cycle of encoding and decoding between two languages. The training process uses innovative unsupervised methods, including a noise model that introduces errors into the data to improve the robustness and accuracy of the translations. The model’s performance is evaluated using BLEU scores [25], In conclusion, While the paper focuses on a new method of evaluation on natural language translation, the underlying technologies and methodologies could be adapted for programming language translation, such as from Java to Kotlin. The unsupervised nature and the ability to learn without direct examples are particularly appealing for scenarios where direct translation examples are limited or non-existent. Better together? an evaluation of AI-supported code translation [30] This paper seeks to establish the practical advantages of utilizing generative machine learning models in relation to code translation tasks. Precisely, it explores the manner in which AI support 4By providing the model with numerous examples of sentence structures and their corresponding translations, it learns the intricacies and linguistic nuances of both the source and target languages 34
influences those programmers who have to translate code from Java into Python. Furthermore, it evaluates if partial or incorrect automatically generated code fragments might serve as productivity and quality enhancing tools for software developers. In the study was found that AI assistance helped reduce the number of errors in code translations this Engineers working with AI support produced significantly cleaner and more accurate code than those working without it. The study also explored the impact of the quality and quantity of AI- generated translations. Impressively, providing multiple AI-generated options was more beneficial than enhancing the accuracy of a single output, suggesting that exposure to various solutions could improve problem-solving approaches among several engineers. In conclusion, while the study focuses on Java to Python, the principles can be extrapolated to our Java to Kotlin project with an AI assistance. Unsupervised translation of programming languages[13] The paper introduces a new way of translating programming languages by use of unsupervised machine translation methods. Transcoder is the new model, a model that can overcome the issues that come with changing code from one programming language into another without the help of parallel corpora. Transcoder uses unsupervised learning to train on large code without parallel data which reduces the need of language expertise and manual adjustments. The robust evaluation comparing 852 parallel functions, with its unit tests to confirm its correctness, makes Transcoder to outperform the rule-based systems5, such as j2py6and a commercial solutions from Tangible Software Solutions.7 While Transcoder has not being tested with Java to Kotlin the approach used in this paper can be highly relevant and valuable for our model. In this thesis, we explore the potential of adapting the Transcoder model, previously untested for Java to Kotlin translation, to our case. Given the model’s proven success across various languages, we believe this adaptation could be both straightforward and beneficial. Summarize and generate to back-translate: Unsupervised translation of programming languages [3] This paper introduces a new approach for unsupervised translation of programming languages using a method called Back-Translation and Summarize-and-Generate technique. The authors propose using English as an intermediary step, summarizing the code into English and then ”translating” the summary into the target language. The paper utilizes a back-translation framework, where the model is initially trained to translate 5AI systems that employ a set of predefined rules to derive conclusions from given data 6https://github.com/natural/java2python 7https://www.tangiblesoftwaresolutions.com/ 35
from the target language back to the source language using generated summaries as intermediates. This helps the model learn without relying on parallel text. This innovative approach offers a new method that can be used in our project for language transition.This paper not only extends the boundaries of unsupervised machine translation but also provides a framework that could be adapted to closely related programming languages, Unified pre-training for program understanding and generation [2] This paper introduces PLBART, Program and Language BART), a bidirectional and autoregressive transformer, a sequence to sequence model pre-trained on a large collection of Java and Python functions and natural language descriptions from Github and StackOverflow, respectively. The goal is to solve numerous challenges like code summarization, code generation, program repair, clone detection, vulnerable code detection as well as code translation by using a pre-training strategy. The model’s versatility can be shown with its evaluations where PLBART has shown higher than or similar performances compared to other state-of-the-art models such as CodeBERT and Graph- CodeBERT. In code summarization, code generation and code translation PLBART outperforms all of the other models, on program repair it achieves better metrics except for GraphCodeBERT, which rivals against finally in vulnerability detection and clone detection where it performs slightly better than its counterparts. This is because PLBART has a function learning language syntax and semantics even when unlabeled data is being used. In conclusion, while the study does not mention Kotlin at all, its principles for Java to Python can be adapted to Java to Kotlin. This due to the model’s ability to learn and translate between different programming languages, coupled with its success in related tasks, suggests it could be adapted to enhance Java to Kotlin translation tools. Unsupervised machine translation using monolingual corpora only [14] The article has introduced an innovative method in machine translation, which relies on unsupervised learning to perform translations between languages without the use of parallel corpora. In doing so, it seeks to eliminate the constraints brought by limited parallel data sources particularly in under-resourced languages using a large monolingual dataset approach. The methodology involves mapping sentences from two different languages into a shared latent space and learning to reconstruct sentences in both languages from this space. The core strategy involves back-translation, where sentences are first translated from the target language to the source language and then back again, progressively refining the translations through iterative training. The model is tested on several language pairs and datasets, proving its capability to achieve competitive translation quality with BLEU scores. 36
This paper focuses on natural languages such as English, French and German. Despite this, the unsupervised approach can be adapted for programming languages like our project, by using techniques that leverage large codebases in both Java and Kotlin, without the necessity of manually selecting parallel code examples. Syntax and domain aware model for unsupervised program translation [18] The paper introduces a new model called SDA-Trans for unsupervised programming language translation. In terms of improving translation of a program from one language into another, largescale parallel corpora are not necessary. This means this approach uses syntax-aware transformer components as part of the model in question instead of the traditional parallel corpora. The model employs an unsupervised learning strategy using a three-stage training process that includes cross-lingual masked language modeling, denoising autoencoding, and back-translation to improve its translation capabilities without parallel data. This model has been evaluated on translation tasks between Python, Java, and C++, demonstrating its efficacy particularly in translating to and from unseen languages during pre-training, As a conclusion, given the structural similarities between Java and Kotlin, SDA-Trans’s syntaxaware translation mechanisms could be particularly effective to our project. Perfection not required? Human-AI partnerships in code translation [29] This paper presents a study on the challenges and limitations of using Large Language Models (LLMs) for the task of code translation. The research investigates the effectiveness of general and specialized code LLMs in translating code across different programming languages including C, C++, Go, Java, and Python. The study is extensive, involving the translation of 1,700 code samples from various benchmarks such as Human Evaluation, BLEU Score and Acceptance through Verification8. A significant portion of the paper is dedicated to analyzing the errors produced by LLMs. The authors developed a taxonomy of 15 categories of translation bugs. The study also compares LLM-based translation with non LLM-based translation approaches. While the paper primarily focuses on languages like Java and Python, the findings are highly relevant to Java to Kotlin translation. The detailed error analysis provides valuable information for developers creating tools for code translation- 8Applying code reviews and testing before integrating code into production 37
7.2 Research table Paper Name Source and target language J→Kt? Model(s) paper Model(s) link Evaluation methods and Datasets CodeGeeX: A Pre-Trained Model for Code Generation with Multilingual Evaluations on HumanEval-X [33] Py ⇔C++ ⇔Java ⇔ Js ⇔Go ✗CodeGeeX2 CodeGeeX2 HumanEval-X CodeScope: An Execution-based Multilingual Multitask Multidimensional Benchmark for Evaluating LLMs on Code Understanding and Generation [32] C++ ⇔Java ⇔Py ⇔ C⇔Csharp ⇔Ruby ⇔ Go ⇔Js ⇔Kotlin ⇔ PHP ⇔Rust ⇔Perl ⇔ D⇔Delphi ✔ GPT-4 GPT-3.5 Code LLaMA LLaMA 2 StarCoder WizardCode Vicuna PaLM 2 GPT-4 GPT-3.5 Code LLaMA LLaMA 2 StarCoder WizardCode Vicuna PaLM 2 CodeScope Understanding the effectiveness of large language models in code translation [23] C⇔C++ ⇔Go ⇔ Java ⇔Py ✗ CodeGeeX2 StarCoder CodeGen CodeGeeX2 StarCoder CodeGen CodeNet Avatar EvalPlus Unsupervised translation of programming languages [13] C++ ⇔Java ⇔Py ✗TransCoder TransCoder BLEU Computational Acc. Reference match Summarize and generate to back-translate: Unsupervised translation of programming languages [3] Java ⇔Py ✗PLBART TransCoder PLBART TransCoder BLEU CodeBLEU Computational Acc. Unsupervised machine translation using monolingual corpora only [14] English ⇔French ⇔ German ✗-Not provided- -Not provided- WMT BLEU Syntax and domain aware model for unsupervised program translation[18] Py ⇔Java ⇔C++ ✗SDA-Trans -Not provided- CodeSearchNet Unit Test Table 9: Summary of More Relevant Research Studies to our Project Source: Self-made 38
7.3 Benchmarks In this subsection we will see a brief explanation of each benchamark that has been used in each of the previously mentioned studies. In some studies like HumanEval-X, features with bot a Dataset and a Bnechmark so we can see them in both subsections HumanEval-X [33] HumanEval-X is a benchmark designed to evaluate the multilingual capabilities of code generation models. It consists of 820 high-quality, human-crafted programming problems with their corresponding test cases. These problems are provided in five programming languages: Python, C++, Java, JavaScript, and Go. The main purpose of HumanEval-X is to assess the functional correctness of code generated by models across different languages. HumanEval-X supports code generation and code translation. For code generation, models use function declarations and docstrings as input to produce corresponding code solutions, while for code translation, models translate code from one programming language to another using function declarations in both source and target languages along with the source code solution. The evaluation metric used in HumanEval-X is the pass@k metric, which measures the proportion of correctly generated code samples9out of multiple attempts, thus providing a robust assessment of the model’s capabilities. HumanEval-X, even though it is the most used benchmark, does not include Kotlin between its supported languages. CodeNet [26] CodeNet is a comprehensive dataset and benchmark suite created by IBM to advance AI research in code generation. It encompasses over 14 million code samples across 50 programming languages, accompanied by extensive metadata and over 4000 coding problems, each one with detailed descriptions and multiple solutions with test cases. The primary goal of CodeNet is to assess the functional correctness of code generated by AI models across different languages. It supports code generation, where models use function declarations and problem descriptions to produce code solutions, and code translation, where models convert code between programming languages. The metric that is used to evaluate model performance consists in once again the pass@k metric10, which measures the proportion of correctly generated code samples out of multiple attempts. 9Code that surpasses correctly the test. 10Pass@k measure how many of these top k solutions are correct. 39
EvalPlus [19] EvalPlus is an advanced benchmark designed to enhance AI research. It includes a rich dataset of high-quality, human-crafted programming problems and test cases across multiple programming languages. Each problem comes with detailed descriptions, input-output examples and constraints. EvalPlus supports code generation, where models produce code solutions from function declarations and problem descriptions, and code translation, where models convert code between different programming languages. The benchmark uses the pass@k metric to evaluate model performance, measuring the proportion of correctly generated code samples out of multiple attempts. BLEU Score [24] The BLEU score (Bilingual Evaluation Understudy) is a key metric for evaluating the quality of text generated by AI models. It works by comparing the model’s output to one or more reference translations, measuring how closely the generated text matches these references through n-gram analysis11. BLEU evaluates unigrams, bigrams, trigrams, and up to four-grams, rewarding closer matches. The BLEU score is precision-based, assessing the accuracy of n-grams in the generated text relative to the reference text, and includes a brevity penalty to avoid artificially high scores from overly short translations. The score ranges from 0 to 1, with 1 indicating a perfect match. Code BLEU [27] CodeBLEU is an advanced evaluation metric specifically designed for assessing the quality of code generated by AI models. Unlike the traditional BLEU score used for natural language, CodeBLEU takes into account the unique structural and functional aspects of programming languages. Similarly to the BLEU score, it evaluates code through n-gram matching, where sequences of tokens in the generated code are compared to those in reference implementations. This helps determine the detailed accuracy of the generated code. In addition to n-gram matching, CodeBLEU incorporates structural matching to ensure the syntactic correctness of the code. This aspect checks whether the generated code follows proper programming patterns and constructs, making it structurally sound. Furthermore, CodeBLEU evaluates the semantic correctness of the code, assessing whether the generated code performs the same function as the reference code. This comprehensive approach ensures that the code is not only syntactically accurate but also functionally correct. By combining these dimensions into a single weighted score, CodeBLEU provides a holistic evaluation of AI-generated code. It is a crucial tool for researchers and developers working on code 11n-gram is a contiguous sequence of n items from a given sample of text, in this case it refers to sequences of words. 40
generation, translation, and completion tasks, helping them identify models that produce highquality, well-structured, and functional code. CodeSearchNet [10] To evaluate model performance, CodeSearchNet includes a benchmark suite that uses metrics like Mean Reciprocal Rank (MRR)[8] and precision at k12. These metrics provide detailed insights into how well models retrieve relevant code snippets based on natural language queries, helping researchers identify areas for improvement. Computational accuracy Computational accuracy is a method of evaluation which involves evaluating the correctness and relevance of the results generated by an AI model. This assessment is crucial for understanding how well the model performs its intended function and for identifying areas where it can be improved. For each task, in our case we are interested in code translation, computational accuracy benchmarks are tailored to measure the model’s performance on that specific task. Various metrics are used to quantify computational accuracy. Common metrics include: Precision, recall, F1 Score, Mean Reciprocal Rank (MRR)13 and Precision at K (P@K) Reference match Reference match refers to the process and method used in evaluating the performance of AI models, particularly in tasks such as information retrieval, code search, and natural language processing. In this context, ”reference match” involves comparing the outputs generated by the AI model to a set of pre-defined correct answers or ”reference” outputs, more specifically, in code translation this consists on pairs of the source language and the target language. The reference Outputs are the correct or ideal outputs that the AI model is expected to produce. In the context of code search, for instance, the reference outputs would be the correct code snippets that should be retrieved in response to a query, and in code translation the reference output would be the correct code in the target language. In conclusion, the AI model generates outputs based on the given inputs, and these generated outputs are compared to the reference outputs. The comparison can be based on various metrics to determine how well the generated outputs match the reference outputs. 12Measures the proportion of relevant results in the top K retrieved items, indicating how many of the top results are relevant. 13Calculates the average of the reciprocal ranks of the first relevant result. 41
Bytecode-pairs dataset To accomplish the task of creating a bytecode dataset, we utilize the previously mentioned tool, bytecode generator. The data was organized as we can see in Figure 9, inside a main folder which uses a hierarchical folder structure: Figure 9: Repository structure Each primary folder represented a project, and within each primary folder, sub-folders contained individual files of the project. Each sub-folder comprised the source code file, the compiled file and the bytecode file. Figure 10: Java, Kotlin and Bytecode files Given that a project can contain multiple files with identical names, the sub-folder naming convention included the file name along with a prefix corresponding to the package name where the 48
file is located. This approach ensured unique identification of files. Sub-folders could contain both Java and Kotlin files, reflecting scenarios where a project transitioned from one language to another while retaining both versions. The bytecode file (class) results from compiling the source code file. Using javac16, we can generate the bytecode file (.bytecode) from the class file (.class). 9.1.4 Tranformation to Transcoder input format With all necessary data collected, the next step involves transforming this data into a format compatible with TransCoder’s preprocessing requirements. As remarked in its repository17, TransCoder employs JSON files in a JSONL format, which are then compressed into gzip files18. Listing 1: Example of a data point expressed in the format compatible with Transcoder. 1{ 2" repo_name ":" TFG / compose - roller - animator ", 3"ref ":" refs / heads / data " , 4"path":" bytecode / compose - roller - animator / myapplication_MainActivity / MainActivity . kt ", 5"copies":"1", 6"content":" package com . chinalwb . myapplication \n\ nimport android . os. Bundle \ nimport android . util . Log \ nimport androidx . activity . ComponentActivity \ nimport androidx . activity . compose . setContent \ nimport androidx . compose . foundation . gestures . Orientation \ nimport androidx . compose . foundation . gestures . scrollable \ nimport androidx . compose . foundation . layout .*\ nimport androidx . compose . foundation . rememberScrollState \ nimport androidx . compose . foundation . verticalScroll \ nimport androidx . compose . material .*\ nimport androidx . compose . runtime .*\ nimport androidx . compose . ui. Alignment \ nimport androidx . compose . ui. Modifier \ nimport androidx . compose .ui . graphics . Color \ nimport androidx . compose . ui. text . TextStyle \ nimport androidx . compose . ui. tooling . preview . Preview \ nimport androidx . compose .ui . unit .dp \ nimport com . chinalwb . compose . rolleranimator . RollerNumberAnimator \ nimport com . chinalwb . myapplication . ui. theme . MyApplicationTheme \ nimport kotlin . random . Random \n\ nclass MainActivity :ComponentActivity() 7{\n override fun onCreate ( savedInstanceState :Bundle?) {\n super . onCreate ( savedInstanceState )\n setContent {\n MyApplicationTheme {\n // A surface container using the ’background ’ color from the theme \n Surface (\n modifier = Modifier . fillMaxSize (),\n color = MaterialTheme . colors . background \n ) {\n Greeting (\" Android \") \n }\n }\n }\n }\n}\ n\ n@Composabl e \ nfun Greeting ( name :String) {\n val scrollState = rememberScrollState ()\n Column ( modifier = Modifier \ n . padding ( horizontal = 16.dp )\n . verticalScroll ( scrollState )\n ) {\n Text (\ n modifier = Modifier . padding ( vertical = 16.dp ),\n text = \" Roller Animator Demo App \" ,style = MaterialTheme . typography .h5)\ n\ n Text ( text = \"\"\"\ n Settings :\n animateOneByOne = false ,\n duration = 600,\n ltr = false ,\n animateToSameNumber = false\n \"\"\". trimIndent ())\n RollerAnimatorDemo (\n animateOneByOne = false ,\n duration = 600,\n ltr = false ,\n animateToSameNumber = false,\n )\n\n Spacer ( modifier = Modifier . height (64. dp ))\n Divider () \n\n Text ( text = \"\"\"\ n Settings :\n 16command which compiles the file in source code .java in bytecode Java .class 17Github: Transcoder dataset 18Single-file, single-stream, lossless data compression file format which has the suffix .gz [17] 49
animateOneByOne = true ,\n duration = 600,\n ltr = false ,\n animateToSameNumber = false \ n \"\"\". trimIndent ())\n\ n RollerAnimatorDemo (\n animateOneByOne = true ,\n duration = 600,\n ltr = false ,\n animateToSameNumber = false,\ n ) \n \n Spacer ( modifier = Modifier . height (64.dp))\n Divider ()\n \n Text ( text = \"\"\"\ n Settings :\n animateOneByOne = true,\n duration = 600,\n ltr = true ,\n animateToSameNumber = true \n \"\"\". trimIndent ())\n\n RollerAnimatorDemo (\n animateOneByOne = true ,\n duration = 600 ,\n ltr = true ,\n animateToSameNumber = true,\n )\n }\n\n}\n\ n@Preview ( showBackground = true )\ n@Composable \ nfun DefaultPreview () {\n MyApplicationTheme {\n Greeting (\" Android \") \n }\n}" 8} Given that our data is stored in a GitHub repository as regular code files, and considering the considerable volume of data that needs to be processed, it became evident that a script was essential to automate the transformation of all this data into the required json.gz files. To address this requirement, we developed a comprehensive script designed to read every file from the repository and extract the necessary information. The script identifies files with extensions .java, .kt, or .bytecode and processes them accordingly, storing the extracted data in the corresponding JSON file for each language. This automation significantly streamlines the data transformation process, ensuring consistency and efficiency. Throughout the project, the script underwent several modifications. Initial versions of the script encountered errors during the preprocessing phase, primarily due to format discrepancies with TransCoder’s requirements. These issues prompted iterative refinements to the script, which are discussed in greater detail in Section 10, ”Problems and Issues.” The final version of the data transformation script, along with a detailed explanation of its functionality, is provided in Appendix D. This appendix includes the complete script code, offering insights into its development and the solutions implemented to overcome the encountered challenges. 9.2 Data preprocessing In order to preprocess data into the model and for its later training we need to dispose from an enough complex and complete dataset for each one of the languages and transform it into the format that TransCoder needs to process the data. In the initial phase of the preprocessing, we created a script that encapsulates all the instructions and commands necessary for preprocessing, the script can be found in Annex H. Once we had the script we utilized the example dataset provided by the authors of TransCoder, available in the official repository that we cloned19. This step was crucial for us to understand the entire execution flow carefully. By incorporating additional print commands as well as using the existing log statements, we were able to gain a more precise understanding of the preprocessing procedures. 19https://github.com/Sirkkouga/TFG/tree/main/data/test_dataset 50
Through this detailed examination, we were able to observe and learn the intricacies of how TransCoder handles preprocessing. This foundational understanding was essential for ensuring that we could accurately replicate and adapt the process for our own datasets. Once we had a firm grasp of the preprocessing steps, we proceeded to input our datasets into the model. It is important to note that each dataset required a unique preprocessing approach. Due to these variations, we will provide a detailed explanation of the preprocessing steps for each dataset individually. Finally, an explanation of the mixed preprocessing, detailing how the model begins to generate mixed files. 9.2.1 Java dataset preprocessing The Java dataset required the least amount of work, due to the base model’s existing proficiency in processing Java source code. We initially introduced our dataset to the model to preprocess its data. During this process, we closely monitored the outputs and logs, which revealed that the training dataset was insufficiently large to be effectively split into training, validation, and test sets. Consequently, the train and validation splits remained void. To address this issue, we transitioned to the second repository we had created, which contained a larger dataset. This change ensured that the dataset size was adequate for the necessary splits. After switching to the larger dataset, the preprocessing phase proceeded smoothly. We successfully tokenized the entire Java dataset and generated the corresponding splits for training, validation, and testing. 9.2.2 Kotlin dataset preprocessing The Kotlin dataset required more effort compared to the Java dataset. This increased complexity was primarily due to the necessity of creating a dedicated Kotlin processor. The code for this processor, along with detailed explanations, can be found in Annex F. After successfully developing the Kotlin processor, the next step was to identify a suitable treesitter[1] parser for Kotlin grammar, as TransCoder utilizes this library to construct the syntax trees, by generating Abstact Syntax Trees (AST), Tree-Sitter facilitates syntax highlighting and structural analysis, which are essential for understanding the syntactic and semantic elements of the code. Our search led us to the Kotlin grammar repository available at https://github.com/ fwcd/tree-sitter-kotlin.git. Upon acquiring the required resources, including the Kotlin processor and the tree-sitter parser, we integrated them into our preprocessing workflow. We then utilized the preprocessing script to handle the data. Consequently, all data was processed accurately and efficiently. 51
9.2.3 Bytecode dataset preprocessing The bytecode dataset required the most effort among the three datasets. This, due to the necessity of creating the bytecode processor, frequent errors encountered during preprocessing, and the lack of sufficient logging in the original code to gather information. Given the absence of an existing tree-sitter parser for JVM bytecode, it was decided to use the IR processor included with TransCoder as a reference due to the similar functionality bytecode plays in our case compared to the IR used in Transcoder (LLVM [15]). Additional logging was implemented throughout the code to detect and diagnose potential errors. This approach allowed for the identification and resolution of various issues that arose during preprocessing. After making the necessary modifications and enhancements, the bytecode dataset could be processed correctly. This ensured that the data was appropriately prepared for the training stage of the project. 9.2.4 Shared preprocessing After being able to preprocess each dataset individually we used the .codes files from each language and the json.gz files to preprocess all the data together. The preprocessing script can be found in Appendix H. This involved extracting and tokenizing the data into .tok files while handling language-specific parsing for Java, Kotlin, and bytecode. The extracted tokens were then deduplicated and split into training, validation, and test sets, ensuring a clean and structured dataset for model training. Additionally, we applied Byte Pair Encoding (BPE) to the tokenized data to create a consistent subword vocabulary, facilitating efficient and accurate model training. This preprocessing ensured that our data was in the correct format, ready for the subsequent training phase to build a robust model for cross-language code translation. 9.3 Executing Training Transcoder for Java to Kotlin Once we had the data preprocessed we could start with the training part of the model. In order to run the training commands we developed a script highlighting the general documentation. We can see the training script in the Appendix I. The training was conducted using Masked Language Modeling, a technique explained in Subsection 8.3. As we detailed, in this part of the training, the model attempts to predict the masked tokens in order to understand each language. To evaluate this training, we use two primary metrics: accuracy and perplexity. Accuracy: Accuracy is a metric that measures the proportion of correctly predicted tokens to the total number of tokens. In the context of Masked Language Modeling (MLM), accuracy is calculated by comparing the model’s predicted tokens against the actual tokens that were masked during training. A higher accuracy indicates that the model is better at predicting the correct 52
tokens, reflecting its understanding of the language structure and syntax. Accuracy is typically expressed as a percentage and is calculated using the formula: Accuracy = Number of Correct Predictions Total Number of Predictions ×100 (1) Perplexity: Perplexity is a metric used to evaluate the quality of a language model. It measures how well the probability distribution predicted by the model aligns with the actual distribution of the data. Lower perplexity indicates a better predictive performance of the model, as it suggests that the model’s predicted distribution is close to the true distribution of the data. Perplexity is calculated using the formula: Perplexity = exp −1 N N X i=1 log P(wi)!(2) where Nis the number of tokens in the sequence, and P(wi) is the probability assigned by the model to the i-th token. In simpler terms, perplexity can be thought of as the exponentiated average negative log-likelihood of the tokens. It gives an indication of how surprised the model is by the actual tokens, with lower values indicating better performance. By using these metrics, we can assess the effectiveness of the training process and the model’s ability to understand and generate code. High accuracy and low perplexity values signify that the model is performing well in its task of predicting masked tokens and understanding the underlying structure of the programming languages it is trained on. After submitting the jobs and fixing errors, the model started iterating through epochs were we started observing and taking some measurements. 9.4 Validation of the trained model In the first values of the perplexity we can see a decrease in values for all the different splits except for the validation and test from the Kotlin dataset. This indicates that Kotlin is the language the model struggles the most. Java, on the other hand, shows no significant upgrades or downgrades through the iterations of the several epoch. Lastly bytecode shows an impressive improvement reducing the level of perplexity between epoch. The observed learning difficulties can be attributed to the inductive bias 20 inherent in transformers [16]. The model’s preprocessing and representation of bytecode might not be capturing the necessary nuances, resulting in higher perplexity and lower accuracy. The inductive bias towards simpler, more symmetric functions may cause the model to overlook complex patterns inherent in bytecode. On Kotlin’s side, the high fluctuation and instability in perplexity for Kotlin suggest that the training data may not be diverse or comprehensive enough to cover the language’s complexity. The 20Assumptions a model makes to generalize from training data to unseen data 53
Figure 11: Perplexity first values model’s inductive bias appear because the model relies on patterns seen during training, leading to poor generalization as indicated by the high test perplexity. In Java as seen in the first epoch indicates that the model quickly learns the simpler aspects of the language but fails to grasp more complex patterns. This is likely due to the inductive bias favoring simpler, more straightforward patterns, causing the model to struggle with more intricate syntactic and semantic rules. Going into detail we can analyse two significant epoch, the first one and the fourth one in order to explain the reason behind this results. 54
Figure 12: Accuracy evolution during MLM The initial epoch of training highlights significant challenges, particularly with bytecode processing. The high perplexity and zero accuracy for bytecode indicate that the model struggles to interpret this intermediate representation. The performance discrepancy between Java and Kotlin also points to areas for improvement. While the model shows some proficiency with Java, the higher perplexity and lower accuracy for Kotlin suggest gaps in the training data or differences in language complexity. The results from the first epoch, as seen in the figure 13, are generally expected for an initial training phase, especially given the complexity of the task. In this fourth epoch we can observe in the validation metrics an indication of mixed results across the different languages. For Java, the validation perplexity has increased to 599.55, and the accuracy remains at 0.00%. This lack of improvement suggests potential issues with the model’s ability to generalize from the training data to the validation set. It may indicate that the model is over-fitting to the training data or that there are fundamental gaps in the data quality. As in Java, Kotlin’s validation perplexity has increased to 1628.83, showing a downhill progress compared to earlier epochs. Moreover, the validation accuracy is still extremely low at 0.10%, suggesting that remains far from achieving reliable translation. This indicates that the model may be getting worse at predicting the structure of Kotlin code, yet it still struggles with correct token prediction. Finally, Bytecode validation results show significant improvement, with perplexity reduced to 742.27 and accuracy increasing to 23.41%. Although this is a positive sign, the high 55
Figure 13: Results of first epoch perplexity and low accuracy highlight the need for model fine-tuning to make bytecode a more effective intermediate representation. In the figures 15 and 12 we can see represented in a graph both values, perplexity and accuracy respectively, and its evolution, in the validation split, which tunes model hyper-parameters and monitor performance during training, and test split, which is used to evaluate the final model’s performance and generalization to unseen data after training is complete, for each language. We can observe that the perplexity values fail to improve significantly during the initial iterations of the first epoch. This lack of progress could be attributed to several factors, as previously discussed. One significant reason might be over-fitting, where the model starts to memorize the training data rather than generalizing from it. Another contributing factor could be a high dependency on hyper-parameter settings, as noted in the literature [9]. The effectiveness of the model can be highly sensitive to these settings, and can lead to suboptimal performance. Additionally, the quantity of data being used for training might not be sufficient to provide the model with the diversity of examples it needs to learn effectively. This insufficient data volume can hinder the model’s ability to generalize well, resulting in perplexity values that do not show significant improvement during the early training stages. 56
Figure 14: Results of fourth epoch 10 Problems and issues faced In this section we discuss all the problems, issues, difficulties that took place during the project. Preprocessing dataset The first challenge encountered, concerning the code, was related to the dataset itself. The dataset was initially so limited in size that it necessitated the use of the secondary repository for both preprocessing and training. This approach diverged from the original plan, which intended to preprocess the data from the first repository to understand its behavior, and then, use the larger dataset to train the model. The second issue identified was the incorrect creation of gzip files. During the process of writing gzip files, an error occurred, resulting in the loss of information. This problem required to review the dataset script creation entirely. Another issue arose during the data preprocessing phase. The process failed to create all the necessary files, which was attributed to the hash used by the architecture. As illustrated in Figure 16, the hash is created using the repository name, which led to a issue. The issue was that, since all data was stored in the same repository, they were assigned the same hash, resulting in all data being counted as originating from a single repository. This problem was resolved by modifying the repository name to be distinct within the RepoID at the moment of creating the json files, which ensured the correct separation and identification of data across different repositories. 57
CES 1.9: Demonstrate understanding in the management and governance of software systems. (Deeply) We achieved this competence through the effective use of version control systems in specific, GitHub, and the adoption of agile methodologies to manage the development process. Regular meetings with the director and co-director. CES 2.1: Define and manage the requirements of a software system. (Quite a bit) Initially, the project’s objectives and specifications were not so clearly defined, this due to the project initial phase being investigation. But trough the project, the requirements were refined based on feedback from testing phases. CES 2.2: Design appropriate solutions in one or more application domains using software engineering methods that integrate ethical, social, legal, and economic aspects. (Quite a bit) As explained in the sustainability section 5 social, economic, and environmental aspects were carefully considered. From a legal perspective, as an open-source project, all the information gathered is accurately referenced. Additionally, all resources used, such as the base TransCoder model, are part of the open-source community. 12.2 Computer science competencies CCO 1.1: Evaluate the computational complexity of a problem, understand algorithmic strategies that may contribute to the solution, and recommend, develop, and implement the one that guarantees the best performance according to the established requirements. (A little) The project involved evaluating the computational complexity of translating Java to Kotlin. Various algorithmic strategies were explored, and the most efficient ones were used. The use of advanced machine learning models and efficient data preprocessing techniques ensured the tool operated within acceptable performance parameters. 64
CCO 1.2: Demonstrate knowledge of the theoretical foundations of programming languages and the associated lexical, syntactic, and semantic processing techniques, and know how to apply them to the creation of design and language processing. (Quite a bit) In-depth knowledge of Java and Kotlin’s theoretical foundations was crucial for this project. The translation tool leveraged lexical, syntactic, and semantic processing techniques to accurately convert source code. CCO 1.3: Define, evaluate, and select hardware and software development and production platforms for the development of applications and IT services of varying complexity. (A little) Throughout the project, careful selection of development and production platforms was undertaken. The project utilized Google Colab for creating and running the scripts needed, we were also granted an access to TSC CALCULA computing services, ensuring access to enough computational resources. Additionally, GitHub was used for version control and collaboration, providing a reliable platform for managing the project’s codebase. CCO 2.1: Demonstrate knowledge of the fundamentals of paradigms and techniques specific to intelligent systems, and analyze, design, and build IT systems, services, and applications in any application domain. (Quite a bit) During the project we demonstrated a solid understanding of intelligent systems. For instance the use of machine learning models, particularly TransCoder, showcased the ability to analyze, design, and construct an intelligent system capable of translating from Java to Kotlin. CCO 2.4: Demonstrate knowledge and develop computational learning techniques, design and implement applications and systems that use them, including those dedicated to the automatic extraction and knowledge from large amounts of data. (Deeply) Due to the approach considered, the project leveraged existing computational learning techniques and applied them to a new problem domain, demonstrating the ability to adapt and extend advanced models for specific use cases. 65
References [1] Tree-sitter: An incremental parsing system for programming tools. https://tree-sitter. github.io/tree-sitter/. Accessed: 2024-07-03. [2] Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, and Kai-Wei Chang. Unified pretraining for program understanding and generation. 2021. [3] Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, and Kai-Wei Chang. Summarize and generate to back-translate: Unsupervised translation of programming languages. 2022. [4] Luca Ardito, Riccardo Coppola, Giovanni Malnati, and Marco Torchiano. Effectiveness of kotlin vs. java in android app development tasks. Information and Software Technology, 127:106374, 2020. [5] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. arXiv preprint arXiv:1409.0473, 2014. [6] Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde de Oliveira Pinto, Jared Kaplan, Harri Edwards, Yuri Burda, Nicholas Joseph, Greg Brockman, et al. Evaluating large language models trained on code. arXiv preprint arXiv:2107.03374, 2021. [7] Facebook Engineering. Android java kotlin migration, October 2022. Accessed: 2024-05-06. [8] Evidently AI. Mean reciprocal rank (mrr), 2023. Accessed: 2024-06-03. [9] Jiatao Gu, Yong Wang, Kyunghyun Cho, and Victor OK Li. Improved zero-shot neural machine translation via ignoring spurious correlations. arXiv preprint arXiv:1906.01181, 2019. [10] Hamel Husain, Ho-Hsiang Wu, Tiferet Gazit, Miltiadis Allamanis, and Marc Brockschmidt. Codesearchnet challenge: Evaluating the state of semantic code search. arXiv preprint arXiv:1909.09436, 2019. [11] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M Rush. Structured attention networks. arXiv preprint arXiv:1702.00887, 2017. [12] Marie-Anne Lachaux, Baptiste Roziere, Lowik Chanussot, and Guillaume Lample. Unsupervised translation of programming languages. arXiv preprint arXiv:2006.03511, 2020. [13] Marie-Anne Lachaux, Baptiste Roziere, Lowik Chanussot, and Guillaume Lample. Unsupervised translation of programming languages. 2020. [14] Guillaume Lample, Alexis Conneau, Ludovic Denoyer, and Marc’Aurelio Ranzato. Unsupervised machine translation using monolingual corpora only. 2017. 66
[15] Chris Lattner and Vikram Adve. Llvm: A compilation framework for lifelong program analysis & transformation. In International symposium on code generation and optimization, 2004. CGO 2004., pages 75–86. IEEE, 2004. [16] Itay Lavie, Guy Gur-Ari, and Zohar Ringel. Towards understanding inductive bias in transformers: A view from infinity. arXiv preprint arXiv:2402.05173, 2024. [17] Library of Congress. Gzip format description, 2021. Accessed: 2024-06-03. [18] Fang Liu, Jia Li, and Li Zhang. Syntax and domain aware model for unsupervised program translation. In 2023 IEEE/ACM 45th International Conference on Software Engineering (ICSE), pages 755–767. IEEE, 2023. [19] Jiawei Liu, Chunqiu Steven Xia, Yuyao Wang, and LINGMING ZHANG. Is your code generated by chatGPT really correct? rigorous evaluation of large language models for code generation. In Thirty-seventh Conference on Neural Information Processing Systems, 2023. [20] Kui Liu, Anil Koyuncu, Dongsun Kim, and Tegawende F. Bissyand`e. Avatar: Fixing semantic bugs with fix patterns of static analysis violations. In 2019 IEEE 26th International Conference on Software Analysis, Evolution and Reengineering (SANER), pages 1–12, 2019. [21] A. Maranzero. Record de producci´on renovable 2024. https://amaranzero.es/academia/ blog/record-produccion-renovable-2024, 2024. Accessed: 2024-05-29. [22] Matias Martinez and Bruno Gois Mateus. Why did developers migrate android applications from java to kotlin? IEEE Transactions on Software Engineering, 48(11):4521–4534, 2021. [23] Rangeet Pan, Ali Reza Ibrahimzada, Rahul Krishna, Divya Sankar, Lambert Pouguem Wassi, Michele Merler, Boris Sobolev, Raju Pavuluri, Saurabh Sinha, and Reyhaneh Jabbarvand. Understanding the effectiveness of large language models in code translation. 2023. [24] Kishore Papineni, Salim Roukos, Todd Ward, and Wei-Jing Zhu. Bleu: a method for automatic evaluation of machine translation. In Proceedings of the 40th annual meeting of the Association for Computational Linguistics, pages 311–318, 2002. [25] Matt Post. A call for clarity in reporting bleu scores. arXiv preprint arXiv:1804.08771, 2018. [26] Ruchir Puri, David S Kung, Geert Janssen, Wei Zhang, Giacomo Domeniconi, Vladimir Zolotov, Julian Dolby, Jie Chen, Mihir Choudhury, Lindsey Decker, et al. Codenet: A large-scale ai for code dataset for learning a diversity of coding tasks. arXiv preprint arXiv:2105.12655, 2021. [27] Shuo Ren, Daya Guo, Shuai Lu, Long Zhou, Shujie Liu, Duyu Tang, Neel Sundaresan, Ming Zhou, Ambrosio Blanco, and Shuai Ma. Codebleu: a method for automatic evaluation of code synthesis. arXiv preprint arXiv:2009.10297, 2020. 67
[28] Marc Szafraniec, Baptiste Roziere, Hugh Leather, Francois Charton, Patrick Labatut, and Gabriel Synnaeve. Code translation with compiler representations. arXiv preprint arXiv:2207.03578, 2022. [29] Justin D Weisz, Michael Muller, Stephanie Houde, John Richards, Steven I Ross, Fernando Martinez, Mayank Agarwal, and Kartik Talamadupula. Perfection not required? human-ai partnerships in code translation. In 26th International Conference on Intelligent User Interfaces, pages 402–412, 2021. [30] Justin D Weisz, Michael Muller, Steven I Ross, Fernando Martinez, Stephanie Houde, Mayank Agarwal, Kartik Talamadupula, and John T Richards. Better together? an evaluation of ai-supported code translation. In 27th International conference on intelligent user interfaces, pages 369–391, 2022. [31] Papers with Code. Humaneval-x dataset. https://paperswithcode.com/dataset/ humaneval-x, 2024. Accessed: 2024-05-20. [32] Weixiang Yan, Haitian Liu, Yunkun Wang, Yunzhe Li, Qian Chen, Wen Wang, Tingyu Lin, Weishan Zhao, Li Zhu, Shuiguang Deng, et al. Codescope: An execution-based multilingual multitask multidimensional benchmark for evaluating llms on code understanding and generation. 2023. [33] Qinkai Zheng, Xiao Xia, Xu Zou, Yuxiao Dong, Shan Wang, Yufei Xue, Zihan Wang, Lei Shen, Andi Wang, Yang Li, et al. Codegeex: A pre-trained model for code generation with multilingual evaluations on humaneval-x. arXiv preprint arXiv:2303.17568, 2023. 68
13 Appendix A Github miner The whole code of Github Miner can be accessed in the following url: https://github.com/ UPCBarcelonaTech/TFG-J2K/blob/main/GitHubMiner.py A.1 Fetch repository language A.2 Mine Kotlin projects 69
B Project builder The complete code can be found in the following url: https://github.com/UPCBarcelonaTech/ TFG-J2K/blob/main/ProjectBuilder.py but we can find the main function here: 70
C Bytecode generator The whole code is in: https://github.com/UPCBarcelonaTech/TFG-J2K/blob/main/BytecodeGenerator. py. C.1 Organizing the files C.2 Removing inconsistencies from dataset C.3 Generate readable bytecode 71
D Data transformation script The complete code can be access in the following link: https://colab.research.google.com/ drive/1_4cNf8b5JQj7M1_nOUa9Thzej5yNk8Yk?usp=sharing D.1 Transforming the data into JSON format D.2 Tranforming into JSON format 72
D.3 Creating the JSONL files and convertion into Gzip 73