1 of 80

Last meeting recap

  • Seguir revisando en google scholar surveys del último año y buscar referencias para ver qué lugar podríamos ocupar en el SOTA
    • Mandar una lista en el canal comentando los que has visto similares y qué aportas sobre cada uno de ellos divididos en
      • <=2023
      • >2023
  • Seguir buscando congresos o revistas

  • Evaluar con BM y sus métricas el agente “de autovía” en otros tramos de las otras ciudades (INFERENCIA)
    • Town 03 parte exterior (3 o 4 tramos de ciudades distintas)
    • Sacar (además de lo que ya sacamos con BM) el histograma de velocidades y distancias respecto al centro
    • Parar en BM cuando llegue a un punto en lugar de usar un timer para parar el experimento

  • Acordar plan para cumplimentar prórroga ordinaria

  • Subir post a blog!!!

2 of 80

DDPG CURRENT APPROACH

  • Curriculum learning
  • Add lane curvature in states
  • Stage 1: Learning W - Rewarding just pos and apply fix throttling. Using reward that highly encourage being centered and prevent zig_zag
  • Stage 2: Learning V with learned W - Reward both pos and speed using throttling to reward while “speed not that important on curves” and “velocities over 120 are bad”. Exploration_w decreased, reward modified to not to be that strict on being centered and W gradients frozen to prevent forgetting W due to noisy complex reward function
  • Stage 3: Fine tuning to learn specific complex scenarios -
    • Modify throttling to speed in reward function to encourage keeping speed instead of applying throttling while facing long straights
    • Facing high speeds in sharp curve

3 of 80

Heatmap action speed

4 of 80

DDPG - Video

5 of 80

DDPG Metrics

V average

6 of 80

DDPG Metrics

Effective distance

7 of 80

DDPG Metrics

deviation

8 of 80

DDPG Metrics

Actions histogram

9 of 80

Generalización agente entrenado en town04

No generaliza en el resto porque no hay curvas pronunciadas ni cruces El agente generalizará en situaciones que ha afrontado en el entrenamiento => solo funciona en los carriles exteriores de las ciudades 3, 5, y y 10

  • Town 01 => Cruces con carriles y no sabe que hacer cuando pierde la visión de los puntos superiores (se para en seco)
  • Town 02 => Curvas mucho más pronunciadas y pierde rápido el punto superior. No sabe cuanto girar y cuanto frenar (pero tengo un agente que sabe circular por ciertos tramos a velocidad pueblo)
  • Town 03 => Cruces en los que no tiene carriles (pero tengo un agente que sabe circular por ciertos tramos a velocidad pueblo)
  • Town 05 => Cruces en los que no tiene carriles y cuestas en las que también pierde el punto de arriba y frena (pero hay tramos muy fáciles)
  • Town06 => Muy facil para “agente ciudad”
  • Town 10HD => Cruces en los que no tiene carriles

10 of 80

Town 01

11 of 80

Town 02

12 of 80

Town 03

13 of 80

Town 04

14 of 80

Town 05

15 of 80

Town 06

16 of 80

Town 10

17 of 80

Análisis de percepción “perfecta” en town01

18 of 80

Análisis de percepción “perfecta” en town02

19 of 80

Análisis de percepción “perfecta” en town03

20 of 80

Análisis de percepción “perfecta” en town04

21 of 80

Análisis de percepción “perfecta” en town05

22 of 80

Análisis de percepción “perfecta” en town06

23 of 80

Análisis de percepción “perfecta” en town10

24 of 80

Generalización

Conclusión => Si no enfrenta ni cuestas en la ciudad, no puede saber como reaccionar a ellas + Estamos tratando de poner en un pueblo un coche entrenado en autovía

Camino a seguir:

  1. Inferencia en otros tramos en los que nuestro agente enfrenta el problema en el que se le ha entrenado
  2. Entrenar el agente en pueblo para tener un agente que funcione bien en resto de escenarios

25 of 80

Generalización DDPG

26 of 80

Agente DDPG “autovia” entrenado en 04: Town06

27 of 80

Agente DDPG “autovia” entrenado en 04: Town10

28 of 80

Generalización SAC

29 of 80

Agente SAC “autovia” entrenado en 04: Town06

30 of 80

Agente SAC “autovia” entrenado en 04: Town10

31 of 80

agente “autovia” entrenado en ciudad 04: Town05

32 of 80

video inferencia agente “autovia” entrenado en ciudad 04: Town05

33 of 80

Generalización PPO

34 of 80

Agente PPO “autovia” entrenado en 04: Town06

35 of 80

Agente PPO “autovia” entrenado en 04: Town10

36 of 80

E.g Histograma V (PPO Town10)

37 of 80

E.g Histograma (center image - center lane) [0, 1] (PPO Town10)

38 of 80

Entrenamiento de agente “pueblo”

  • entrenando en Town 01 => Imposible con el setup actual. Cuando afronta una curva intermedia y sigue recto, le da premio, pero no tiene manera de diferenciar ese escenario de una curva final en la que hay arcen, por lo que no aprende a girar (introducir lidar?)
  • Entrenando en Town 02 => mismo caso que town01
  • entrenando en Town 03 => Conseguido agente que afronta bastantes situaciones bien. A analizar cuales son las que no supera
  • Entrenando en Town 05 => Conseguido agente que afronta bastantes situaciones bien. A analizar cuales son las que no supera
  • Entrenando en Town 06 => Conseguido agente que afronta bastantes situaciones bien. A analizar cuales son las que no supera
  • Entrenando en Town 10 => Conseguido agente que afronta bastantes situaciones bien. A analizar cuales son las que no supera

39 of 80

Video en Town06 de agente entrenado en Town03

40 of 80

En Town06 de agente entrenado en Town03

41 of 80

En Town10 de agente entrenado en Town03

42 of 80

En Town04 de agente entrenado en Town03

43 of 80

E.g Histograma V (PPO Town03)

44 of 80

E.g Histograma (center image - center lane) [0, 1] (PPO Town03)

45 of 80

Posibles eventos para publicar

46 of 80

Related articles < 2024 (None describes quantitative analysis like agent braking on curves and throttling otherwise)

https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=10309299 (PPO Vs DDPG. Camera + lidar and obstacles detection => TORCS instead of Carla. Not quantitative analysis just rewards. Using TrackPos sensor and angle sensor directly instead of a camera to infer the states IT HAS AN INTERESTING COMPARISON OF PPO AND DDPG RELATED PAPERS)

https://link.springer.com/article/10.1007/s11042-021-11437-3 DQN Vs DDPG Carla. Waypoints provided by CARLA path planner or by image using segmented image and CNNs. Not perceptions comparison but performance comparison with those perceptions. Small track in town01. Not quantitative analysis, not talking about speed, zig-zag, etc. Not talking a

47 of 80

Related articles >= 2024 (None describes quantitative analysis like agent braking on curves and throttling otherwise)

https://www.huang-zilin.com/VLM-RL-website/ En este, comparan distintos métodos en 1 sola ciudad (Town02) con tráfico denso y a velocidades en torno a 17km/h y contemplan que algunos algoritmos tengan colisiones o menor estabilidad. Algunos incluso chocan o invaden carriles. Solamente exponen sus métodos y algoritmos y sacan conclusiones. Estos no tienen muy buenas métricas pero muestran videos muy chulos.

https://arxiv.org/pdf/2402.16720 (model-based) En este afrontan el problema discretizando las acciones, lo que obviamente hace que sea mucho más facil aprender y usan información privilegiada del simulador eliminando ruido en la percepción. Las métricas son muy escasas (sólamente score en los leaderBoard de carla) y también relatan fracasos con algunos algoritmos (e.g PPO achieved remarkably low scores, a consequence of its rapid convergence to local optima, beyond which the policy ceases to improve further even with the help of the reset technique. We argue that the reason for this phenomenon is that after each reset, PPO has to relearn the policy from the trajectories stored in the replay buffer, which contain inherent reward noise due to the AD characteristics. Conversely, a model-based planner can get accurate and smooth rewards from the world model.” y comenta todas las iteraciones “brik” sin entrar en detalle de training metrics ni inference metrics de cada uno. Solo su experiencia subjetiva y success rate.

https://arxiv.org/abs/2407.02521 Lane changing focused on vehicle path following and PPO vs SAC vs DQN

48 of 80

Related articles >= 2024 (None describes quantitative analysis like agent braking on curves and throttling otherwise)

https://rrinformation.ru/en/journal/keyword/Stable%20Baselines%203/ CARLA PPO vs DDPG vs SAC with sb3. Target speed of 30km/h. Just in russian. Does not explain features extraction. Does not compare training convergence, Does not compare perceptions. Does not compare curriculum learning. Does not explain the town used neither the complexity of the track section or curves Vs straights comparison. Does explain the reward very well and kind of the states used, but not the actions applied.

https://www.researchgate.net/publication/377354348_Reinforcement_Learning-Based_High-Speed_Path_Following_Control_for_Autonomous_Vehicles Este hace una buena comparativa de estrategias (GAIL, SAC y LQR) y usando percepción con cámara para mantenerse en carril a altas velocidades y proporciona buenas métricas cuantitativas

https://arxiv.org/abs/2501.04982 Este completa un circuito con trafico ligero en ciudad 7 que no tiene salidas y sin adelantamientos. Utiliza PPO y VAE del mismo modo que yo usaba YOLOP. No menciona rizado ni métricas detalladas como comportamiento en curvas. Su representación de la recompensa es peor que la mia y sus resultados similares. Explica como utilizando currículum learning el agente aprende mejor, y permite que el agente colisione, mencionando que choca menos con su agente que ha usado currículum learning.

Las métricas en inferencia son más ricas las mías y parece que no se vuelven locos en que el agente sea perfecto, si no en explicar como una técnica en concreto mejora el comportamiento del agente. Y las velocidades son mucho más bajas que las nuestras. (editado)

49 of 80

Our sumarized history

  • Perceptions comparison on centered on lane images => yolop is the best
  • Performance with yolop => not braking in curves in DDPG neither PPO
  • Using perfect perception => braking in curves in DDPG. Not in PPO.
  • Training process refinement (Curriculum, project states, abs(d_0) state and reward) => braking both in DDPG and PPO. Applied to SAC
  • Conclusions of performance improvement Yolop Vs perfect?? Hypothesis: YOLOP bad on non-centered on lane images Vs perfect harming training

50 of 80

En el corto plazo, podemos añadir valor en:

Reconocer que lo que tengo es limitado, pero he visto un rango de sofisticación muy amplio en el SOTA, por lo que yo lo intentaría publicar mientras seguimos avanzando y poder así recibir más feedback:

  • Comparación cuantitativa de algunos mecanismos de percepción (3) y su importancia en el comportamiento del agente. (Algunos artículos comparan diferentes "configuraciones", nosotros podríamos hacerlo utilizando distintos mecanismos de percepción).
  • (Reintentar este nuevo enfoque con YOLOP y MobileNet o agregar la "comparación de cámaras utilizadas" al artículo y mostrar el empeoramiento del rendimiento al usar una percepción de imágenes más ruidosa. Esto añadiría más valor a la sección de conclusiones al acercarse más a una solución realista y enfatizar por qué una percepción clara y robusta es importante).
  • Podemos aplicar regresión lineal sobre YOLOP para completar segmentos no percibidos (con regresión cuadrática, el rendimiento mejoró).
  • Se ha estado trabajando en evolucionar BM para interpretar mejor lo que aprende el agente (mapas de calor con decisiones en función de los estados, mapa de calor con la recompensa en distintos tramos, evolución de acciones en curvas y rectas en el entrenamiento, histogramas v y d, análisis perceptivos, etc.). Algo crucial según el survey https://www.sciencedirect.com/science/article/pii/S0968090X2400175X

51 of 80

the scalability and transferability of RL solutions pose significant challenges, particularly for racing and high-speed maneuvers that require unparalleled precision and adaptability across diverse driving scenarios and vehicle types. Equally crucial is the interpretability and trustworthiness of RL-driven decisions, especially for tasks with high stakes like emergency maneuvering and intersection management, where user acceptance and regulatory compliance hinge on the clarity and reliability of algorithmic choices. This underscores the importance of advancing methods to enhance the transparency and understandability of RL algorithms.

52 of 80

Util. Apoyando la respuesta que me disteis en su momento de “se pueden utilizar mecanismos para corregir el comportamiento del agente CUANDO AFRONTEMOS SITUACIONES MÁS COMPLICADAS”

En argot AD lo podemos calificar como “safety-checker”

53 of 80

En el corto plazo, podemos añadir valor en:

  • Impacto del algoritmo en la recompensa y diseño del enfoque (algunas recompensas funcionan en algoritmos off-policy pero no en on-policy).
  • Curriculum Vs. No curriculum - Comparación del tiempo de convergencia/rendimiento + métricas cuantitativas.
  • DDPG vs. PPO vs. SAC con la misma recompensa y estrategia de entrenamiento - Comparación del tiempo de convergencia y métricas cuantitativas.
    • Del mismo modo que existen surveys, hay un subset de papers que se centran no en mejorar la performance de modelos ya existentes, si no de compararlos de cara a concluir en qué circunstancias o aspectos unos superan a otros (E.g�Soy un investigador y me planteo cual de los algoritmos existentes utilizar para abordar una tarea concreta en un tipo de ciudad concreto con un tipo de sensores específico. O como parte de mi sistema jerárquico en el que utilizo distintos agentes en función del problema que afronten. Este tipo de comparativas y sus conclusiones puede ser suficiente aporte para arrojar luz sobre el mejor punto de partida de otros papers)

54 of 80

Donde podemos apuntar:

  • Aunque tengamos margen para intentar contribuir con el trabajo actual dado el precedente de algunos papers, hay otros más potentes (y más escasos) que abordan:
    • Control adaptativo con tráfico denso
    • Pedrestrians
    • Benchmarks
    • Tecnologías más de moda como LLMs/VLMs
    • Planes más sofisticados como video prediction o multi-agent models
    • Escenarios más complejos como condiciones climatológicas adversas
    • Sim to Real world
    • Situaciones críticas con alta probabilidad de accidente
    • Aún más conflicto de objetivos con mayor riesgo de agentes suboptimos (velocidad, suavidad, consumo, etc)
    • Gestión de semaforos (US o EU) en cruces
    • Cooperative Multi-Agent Reinforcement Learning

  • Otras sugerencias de tesis no encontradas aún en papers
    • Ethical parametrization of RL agent
    • Improvement on critical situations preventing accidents incorporating not usual inputs like horn sounds
    • Parametrization according to some personal criteria (speed, smooth driving, gas savings…)
    • Perception robustness to better fit the simulation-real world gap (our perception is quite fragile and small camera movements greatly impact on agent behavior. We could explore using different cameras, improving generalization, using more perception points, training on preprocessed image instead of extracting waymap points, etc.
    • Herramienta de interpretabilidad tipo “feature importance”. Alterar estados en inferencia para mostrar en plots qué relaciones parece haber aprendido el agente y qué alteración de qué estados lo empeora más.
    • De cara a cubrir el gap sim2real, se podría utilizar la transferencia entre RL y BM + distintos tipos de percepciones y coches para tratar de hacer un agente robusto a pequeñas alteraciones. Ahora mismo, cambiando un punto de la imagen 2 cm abajo supone cambios bruscos en el comportamiento del agente, pero podemos trabajar en minimizarlos.
    • Cumplir normas de tráfico está menos explorado según el survey

55 of 80

Objetivos tentativos

  • Este mes => Elegir el objetivo de la tesis para poder plantear mejor las tecnologías (algoritmos, sensores, sistemas perceptivos, etc) y escenarios a afrontar desde un principio.
  • Agosto 2025 => Presentar artículo en revista o conferencia menor
  • Octubre 2025 => Ser capaces de gestionar tráfico denso con alguno de los 3 algoritmos (Depende de objetivo decidido)
  • Junio 2026 => Empezar a tener resultados favorables en objetivo de la tesis
  • Septiembre 2026 => Empezar a redactar artículo con mayor relevancia y tesis
  • Marzo 2027 => Presentar artículo en revista o conferencia de mayor peso
  • Abril 2027 => Empezar proceso de revision de tesis y últimos remates

56 of 80

57 of 80

Next GOALS

  • Mirar en SOTA en qué estado está la gestión de convoys autónomos
  • Añadir condición de parada cuando se salga del carril en inferencia
  • Histogramas en mismos rangos x

  • Q1, Q2, Q3 y Q4 en revistas => lista jcr
  • Congresos https://scie.lcc.uma.es/ (idealmente en clase 1 y clase 2)

  • Pedir prórroga mediante EID

  • Subir post a blog!!!

58 of 80

This year courses

59 of 80

Afterward GOALS

—--------------------------------------------------------------MID TERM---------------------------------------------------------------------------

  • Next milestones:
    • achieve good performance with ddpg, ppo, sac (and others if possible like a2c or rl-gan-net read on articles)
    • Paper and present on any event
  • Encourage shoft driving punishing brakes
  • Train with perfect and infer with YOLOP or laneDect?
  • Start thinking about thesis scope so I can better nail the articles, experiments, problems and pace to the final objective: (This is my 5th year = last formal year previous to request an extension up to more 2 years)
    • Improvement on critical situations preventing accidents (e.g incorporating not usual inputs like horn sounds)
    • Experiment with vehicles communication (Cooperative Multi-Agent Reinforcement Learning) to improve performance in some scenarios like cross or roundabouts
    • Ethical parametrization of RL agent
    • Complicated perceptions RL agent adjustments to improve on hard weather conditions (fog, hail)
    • Parametrization according to some personal criteria (speed, smooth driving, gas savings…)
    • Perception robustness to better fit the simulation-real world gap (our perception is quite fragile and small camera movements greatly impact on agent behavior. We could explore using different cameras, improving generalization, using more perception points, training on preprocessed image instead of extracting waymap points, etc.)

—--------------------------------------------------------------LONG TERM---------------------------------------------------------------------------

  • Hyperparameter tuning with optuna
  • Carla leaderboard
  • Implementation of curriculum learning to speed up the training process & favor generalization (article lecture)
    • First learn on easy tasks (straight lines)
    • Then randomize with curves to right
    • Then randomize with curves to left
    • Then randomize with harder perceptions
    • Then randomize with perturbations
  • Hierarchical RL with each agent with a subset of the problem actions to simplify training and leverage better performance
  • Train ddpg in several cities so it encounter more scenarios and select other different cities with similar scenarios (but not exactly) the same to test generalization
  • Parallel training with several envs on several towns?? Los experimentos con ppo son lentísimos y puede ayudar lo que dice el curso al respecto
  • Finding courses for this year

60 of 80

ARTICLE

https://www.overleaf.com/project/66406d7efa4a295ac30a9389

  • Future work: ultimo parrafo seccion conclusiones
  • Describir problema y objetivo de la solución al final de la introducción (Qué, no cómo + motivación y tus contribuciones)
  • No darle mucha importancia a research tools. Mencionar herramientas y poco más en alguna otra sección.
  • Después de Research tools -> Diseño/Arquitectura (Podría reemplazar Agent configuration) (Cómo lo has hecho)
  • La mejor solución, ponerla en sección de arquitectura/configuración
  • Demostrar que funciona bien (fuera de comparisons)

61 of 80

MATERIAL ARTÍCULO

Sería sobre la aplicación de seguimiento visual de carril usando técnicas de DRL

variadas (DDPG, PPO, también SAC metiendo a Fran Vázquez, que ha progresado en esa línea tras su TFM)

https://jderobot.slack.com/files/UF9C849LJ/F073CCGCD96/phd-rodrigo-uah.pdf en los capítulos 6 y 7 de cómo se hacen estas cosas

Conferencia -> https://jderobot.slack.com/files/UF9C849LJ/F073CBVJF9N/cfp-robot2024.pdf

62 of 80

GOLDEN RULES

  • En training siempre en modo síncrono y nunca más rápido que en inferencia

  • Ciudad 7. Carriles continuos pero cuesta -> no probar aún porque es complicada.
  • Ciudad 4. Llano pero linea discontinua en el carril central. Idea de Pedro, implementar con lane detector y ñapas que han utilizado los del TFG de Roberto.
  • Trastear con el resto de ciudades.
  • Tener en cuenta que la aceleración y steering funcionan diferente de gazebo -> Trastear para averiguar exactamente como funcionan (en gazebo le marcas m/s y acelera hasta que lo consigue, en CARLA le marcas el empuje con limitación de velocidad, pero no la velocidad).
  • Opción para curvas cuando se aborden escenarios más complejos:
    • Regresión cuadrática para detectar curvas en el horizonte
  • Paper https://link.springer.com/article/10.1007/s41870-023-01412-6 -> pueden meterse ñapas pero tratar de no hacerlo

63 of 80

Useful material

64 of 80

CAMINO DE PEDRO

  • Qlearning en Town07
    • Percepción de RGB a rojos para discretizar las lineas de los carriles y poder obtener el centro
    • Hasta 20km/h
    • Problema -> Hay un tramo muy complejo con subidas y bajadas. En las bajadas pierde la percepción y se embala
  • Qlearning en Town04
    • Autopistas grandes, carriles grandes. Facil
    • Problema1: Linea derecha continua pero el resto son discontinuas => lane detector con Pytorch (que si no va muy en el centro pierde la linea)
    • Solución1: Pasar a tomar como percepción solamente la linea derecha
    • Problema2: Es dificil calcular el centro del carril en base a eso y es poco generalizable
    • Finalmente consiguió llegar a 30Km/h
  • DDPG en Town04
    • No consiguió hacerlo funcionar en CARLA aunque funcionaba en GAZEBO
  • DQN en Town04
    • Descubrimiento del modo síncrono, que hay que ponerlo explícitamente a true. Además hay que tener cuidado con la jerarquía de RL-Studio. Se arregló y ahora también funciona bien en lamdau
    • Intento de hacerlo multiproceso para poder lanzar varias simulaciones a la vez
    • Intento de implementar el lane_detector con regresión para aumentar la linea cuando se ve parcialmente. Aún así se pierde a veces, por lo que quizá haya que resetear la simulación a la mínima
    • Ahora está probando método de Sergio RGB con carriles continuos Vs lane detector con regresión Vs solamente detección carril derecho
  • TODO Aquí -> https://github.com/JdeRobot/RL-Studio/tree/carla_followlane_straight_line
    • Agents > auto_carla

65 of 80

How to record carla then infer Yolop

Start manual_pilot.py, Tab to select 1st view camera. R to toggle recording.

Then go to yolop directory and python tools/demo.py --source ../../CARLA_0.9.13/PythonAPI/examples/_out/

66 of 80

Reward written

function_reward=(β⋅n−S∑i=1n​(1−Di​)​)+((1−β)⋅(V⋅n−S∑i=1n​(1−Di​)​))−punish

Where:

punish={1if V<20otherwisepunish={10​if V<2otherwise​

  • ββ: is the weight assigned to the term involving the inverted distance errors. It can take any value between 0 and 1, inclusive.
  • θθ: is the threshold above which we consider the perception as invalid. It represents the maximum allowed error in the perception. If a distance error exceeds θθ, it is considered unreliable or invalid.
  • SS: represents the count of states (distance errors) above the threshold θθ. If S<3S<3, the experiment is reset. This implies that if there are not enough reliable perceptual states, the experiment restarts to ensure accurate perception.
  • VV and DD: are normalized to be between 0 and 1.

67 of 80

Follow lane History

  • Perceptions comparison on centered on lane images => yolop is the best
  • Performance with yolop => not braking in curves in DDPG neither PPO
  • Using perfect perception => braking in curves in DDPG. Not in PPO.
  • Training process refinement (Curriculum, project states, abs(d_0) state and reward) => braking both in DDPG and PPO. Applied to SAC
  • Conclusions of performance improvement Yolop Vs perfect?? Hypothesis:
    • YOLOP bad on non-centered on lane images Vs perfect harming training (Easy to prove)
    • Applied linear regression over YOLOP to complete non perceived segments (with quadratic regression it improved and we could also add this comparison to the article)
  • Retry this new approach with YOLOP quadratic to add the “camera used” to the article and show the performance worsening of using noisier image perception?? It would add more value to the conclusions section by getting closer to a realistic solution and emphasiting why clear and robust perception is important

  • Things we can add to the SOTA with this article (not found altogether in any article)
    • Quantitative comparison of some perceptions mechanisms (3)
    • Impact of non perfect perception Vs perfect perception = need of much more precise approach and reward to make it work. Much simpler with perfect perception, so better to first investigate with this out of the equation to faster iterate (compare convergence times and extrapolate to experiment times)
    • Impact of algorithm on the reward and approach design (some rewards and approaches working on off-policy algorithms not working in on-policy)
    • Comparison of convergence time and Quantitative performance with curriculum and non curriculum in DDPG (and states that even non convergence with PPO)
    • Comparison of convergence time and Quantitative performance yolop vs perfect
    • Comparison of convergence time and Quantitative performance DDPG vs PPO vs SAC with same reward and approach

68 of 80

Related russian article result

The training lasted 300000 steps divided into 4 episodes of 75000 steps each.

The results of which can be seen in the table below.

Table

Comparison of algorithms

Table

Comparison of algorithms

Algorithm

SAC

DDPG

PPO

Total distance 1144.14 m

1144.09 м

1142.67 м

Total

2534.94

2325.10

2463.50

remuneration

Average speed

21.14 km/h

21.88 km/h

21.60 km/h

Average deviation

0.052 м

0.099

0.046

from the center

Mean

0.868

0.822

0.862

remuneration

Success rate

100%

100%

100%

episodes

Based on the information provided, the following conclusions can be drawn about the comparison of the three

algorithms:

1. SAC (Soft Actor-Critic) algorithm:

- Shows the best results in terms of total distance (1144.14 meters) and total

reward (2534.94) among the three algorithms.

- Has the highest mean values of speed (21.14 m/s) and reward (0.868) with the

with the smallest standard deviations.

- Demonstrates the lowest mean values of deviation from the center of the lane (0.052 m) and the

the smallest standard deviations of this metric.

- All 4 episodes were successfully completed (100% success rate).

2- DDPG (Deep Deterministic Policy Gradient) algorithm:

- Performs slightly worse in terms of total distance (1144.09 m) and

total reward (2325.10) compared to SAC.

- It has higher average speed values (21.88 m/s) but larger standard deviations.

deviations.

- Shows larger mean values and standard deviations from the center of the lane vs.

compared to SAC.

All 4 episodes were successfully completed (100% success rate).

3. PPO (Proximal Policy Optimization) algorithm:

- Performs slightly worse in terms of total distance (1142.67 m) and

total reward (2463.50) compared to SAC.

- It has mean values of speed (21.60 m/s) and reward (0.862), and the

standard deviations of these metrics that are between the SAC and DDPG results.

- Demonstrates slightly larger mean values and standard deviations from the center of the

of the band compared to the SAC.

- All 4 episodes were successfully completed (100% success rate).

Based on the data presented, it can be concluded that the SAC algorithm shows the

the best results among the three considered algorithms. It demonstrates the highest values of total

distance and total reward, as well as the best stability indicators in the form of

smaller standard deviations. In addition, the SAC algorithm shows the smallest deviation

from the center of the lane, indicating smoother and more precise driving. Thus,

SAC can be considered as the most preferable algorithm among the presented algorithms.

CONCLUSSIONS

In this study, a rigorous comparative analysis of three

advanced deep reinforcement learning algorithms: DDPG, PPO and SAC, in the context of an unmanned car driving task in the CARLA simulator.

driving an unmanned car in the CARLA simulator. Experimental results showed,

that each of the algorithms has its own strengths and weaknesses, but the SAC algorithm stood out as the most effective in this task.

as the most effective in this task, providing high stability and accuracy of the

control, as well as the best total distance and reward performance. The results

of this study confirm the potential of applying deep reinforcement learning

in autonomous transportation systems and provide valuable recommendations for their practical

applications.

69 of 80

Related not that close

DDPG, SAC, PPO (Reinforcement Learning Algorithms):

  • [10] Deep Reinforcement Learning for Autonomous Driving: A Survey

Autonomous Driving:

  • [2] Multi-Modal 3D Object Detection in Autonomous Driving: A Survey
  • [3] Rule based system to follow a lane
  • [8] Machine Learning in Autonomous Vehicles: A Survey
  • [9] Deep Learning for Autonomous Vehicles: A Comprehensive Survey
  • [11] Learning to Drive in a Day
  • [12] End-to-End Driving via Conditional Imitation Learning

Perception Mechanisms:

  • [18] YOLOP: You Only Look Once for Panoptic Driving Perception
  • [19] Towards End-to-End Lane Detection: An Instance Segmentation Approach

Curriculum Learning:

  • [14] Curriculum Learning
  • [15] Automated Curriculum Learning for Neural Networks

… Some more focusing on just solving a specific part of the problem we faced which we used to integrate our solution

70 of 80

REWARD

With this we are not just telling the agent “the faster the better” but we are also telling “if you are fast and deviating, it is better that you decelerate”. Otherwise, we are not helping the agent to realize that, and it is difficult for it to realise that braking, it will be easy to keep centered

71 of 80

PPO Inferencia con

PPO PREVIOUS APPROACH

  • Retrain: gradually decrease log_std
  • Retrain: Decrease and increase log_std at intervals
  • Train from scratch with a simpler reward function
  • Train from scratch with a bigger network
  • Increase/decrease coef_entropy
  • Starting with random speeds
  • Tanh in last layer
  • Normalize states and rewards
  • Trying curriculum learning (first w), then high speeds, then sharp curves, epsilon 0.15

72 of 80

PPO Inferencia con

PPO CURRENT APPROACH

  • Curriculum learning
  • Add more waypoints and lidar distance to states
  • Rewarding throttling instead of speed on centered straights (state[0] close to 0) while keeping the same signal “speed not that important on curves” and “velocities over 120 are bad”. In this way we give a clearer short term signal regarding the taken action

*Read that ppo in sb3 is not optimized to use replay buffer, so

  1. it is focused on last states and tends to generalize, so it is struggling to learn more specific scenarios like braking on curves
  2. It works better with short-term rewards while ddpg handle better long-term rewards

73 of 80

PPO

self.ppo_agent = PPO(

CustomPolicy,

self.env,

policy_kwargs=dict(

net_arch=dict(

pi=[32, 32, 32], # The architecture for the policy network

vf=[32, 32, 32] # The architecture for the value network

),

activation_fn=nn.ReLU,

log_std_init=-0.5,

ortho_init=True,

),

max_grad_norm=0.5,

learning_rate=linear_schedule(0.0002),

gamma=0.95,

gae_lambda=0.95,

ent_coef=0.01,

clip_range=0.1,

batch_size=1024,

verbose=1

)

74 of 80

PPO CURRENT APPROACH - Video

  • Working on implementing “show state inputs” on BM inference

75 of 80

PPO CURRENT APPROACH

Heatmap speed action same town

76 of 80

Front car adaptative speed

77 of 80

Front car

1. Incorporar LIDAR como estado adicional en la red existente

En este caso, amplías la entrada de tu red ya entrenada para incluir los datos del LIDAR (distancia y velocidad relativa de los coches de adelante) y vuelves a entrenarla, ahora con escenarios donde haya coches en la vía.

Ventajas:

Simplicidad estructural: Tienes un único agente que aprende a controlar tanto el seguimiento del carril como la adaptación a los coches de adelante, lo que simplifica la arquitectura general.

Coordinación implícita: Al ser una sola red, las decisiones de velocidad y dirección estarán mejor integradas, evitando posibles conflictos entre módulos. Por ejemplo, tu red podría aprender automáticamente a reducir la velocidad en curvas si hay un coche adelante y adaptar el giro del volante.

Menor riesgo de inconsistencias: Con una sola red, es menos probable que las decisiones de velocidad y dirección entren en conflicto.

Desventajas:

Mayor tiempo de entrenamiento: Necesitarás volver a entrenar desde cero o reentrenar cuidadosamente tu modelo actual para que incorpore los nuevos datos, lo que puede llevar más tiempo.

Reentrenamiento complicado: Si tu red ya está bien ajustada para seguir el carril a alta velocidad, añadir la funcionalidad de ACC (control adaptativo de crucero) podría perturbar el comportamiento aprendido, especialmente si tu función de recompensa no está bien diseñada.

---

2. Añadir una segunda red neuronal para gestionar la velocidad

Aquí mantienes tu red actual enfocada exclusivamente en seguir el carril y añades una nueva red que se encargue de gestionar la velocidad en función de los datos del LIDAR.

Ventajas:

Reutilización del modelo existente: No necesitas modificar la red ya entrenada, lo que preserva su comportamiento aprendido y te permite aprovecharlo directamente.

Modularidad: Al separar las tareas, puedes depurar y optimizar cada red de forma independiente. Esto también facilita el mantenimiento del sistema y la incorporación de nuevas funcionalidades en el futuro.

Entrenamiento más rápido: La nueva red solo necesita aprender a ajustar la velocidad, lo que puede reducir significativamente el tiempo de entrenamiento.

Desventajas:

Posibles conflictos entre módulos: Al separar las tareas, debes garantizar que la red de velocidad y la de control lateral trabajen de manera coordinada. Por ejemplo, si la red de velocidad decide frenar de golpe en una curva, esto podría afectar al comportamiento de la red de dirección.

Intercambio de información limitado: Si la red de velocidad no tiene información directa del carril o de las curvas, podría tomar decisiones subóptimas (como mantener una velocidad alta en una curva cerrada).

---

Estado del Arte y Recomendación

En el estado del arte, los sistemas modernos tienden a preferir arquitecturas modulares, donde se dividen las tareas de control lateral (seguir el carril) y control longitudinal (velocidad y distancia). Esto se debe a:

1. Facilidad de optimización: Es más sencillo diseñar y ajustar cada módulo por separado.

2. Flexibilidad: Puedes intercambiar componentes (como cambiar el algoritmo de ACC) sin necesidad de reentrenar todo.

3. Interpretabilidad: Es más fácil entender qué módulo está fallando si hay un problema.

Por lo tanto, te recomendaría implementar una segunda red para gestionar la velocidad y la distancia al coche de adelante. Asegúrate de que ambas redes compartan información relevante si es necesario, como la velocidad actual y las curvas próximas.

Si decides seguir este enfoque, una buena estrategia es usar el LIDAR como entrada principal para la segunda red y configurar la función de recompensa para equilibrar:

Mantener una distancia segura.

Evitar frenados/aceleraciones bruscas (para confort y eficiencia energética).

Coordinar con el módulo de seguimiento del carril, ajustando la velocidad en curvas.

78 of 80

Front car

  • Radar or lidar. Lidar looks more reliable. E.g of articles using radar and/or lidar:
  • Según este artículo y mejor integración con rl-studio + stable baselines, es buena idea utilizar diferentes componentes. Uno para el path planing (w y v) y otro para regular velocidad manteniendo la distancia con el coche de enfrente (System to reuse the learned model and enhance easier system iteration and better models specialization and convergence + reusability of different agents trained with different objectives (smooth, efficiency, speed, aggressive driving, etc)
  • Este otro usa una sola red https://doi.org/10.1109/TVT.2024.3352543, pero ojo!! Usan correctores manuales en los actuadores para mantenerse en el carril sin rizado. Seguramente expermientan la dificultad de hacer al coche aprender todo con una única función.

79 of 80

ACC. TFM Enrique Sinojara

  • https://gsyc.urjc.es/jmplaza/students/tfm-deeplearning-autonomous_driving-enrique_shinohara-2023.pdf DONE
    • TFM => Imitation learning => Imagen -> CNN -> steer + thorttle/brake
    • My approach => Reinforcement learning => Imagen => CNN => Waypoints => DDPG => steer + throttle/brake
      • Según he leido, imitation learning puede aprender directamente de la imagen porque es la propia red la que mapea una imagen a una acción usando aprendizaje supervisado. Con Reinforcement learning, todos los artículos que he leido utilizan lidar para añadir distancia al coche de enfrente como un estado adicional, pero si por algún motivo queremos evitarlo, podría explorar si YOLOP da algo como la distancia (no solo detección de objetos).
    • 81% éxito en Town01. Entiendo que nuestro objetivo es el 100% y lo veo más factible con LIDAR/RADAR
    • No parece que adapte la velocidad al coche delantero, más bien una detención ante obstáculos, frenando cuando está cerca y acelerando cuando este se aleja (con foco en hacerlo de manera progresiva y segura). Los artículos de ACC que he leido hacen referencia a una adaptación de la velocidad gracias al uso de lidar y determinadas heurísticas

80 of 80